Angular Tutorial 0/42 lessons ~6 min read Lesson 12

    Angular Conditional Rendering

    Learn Angular conditional rendering with modern @if, @else if, and @else control flow, traditional *ngIf, component state, Signals, authentication, role-based UI, feature flags, performance, and best practices.

    Course progress0%
    Focus
    32 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Learning Objectives

    By the end of this lesson, you will understand:

    • What Conditional Rendering means in Angular.
    • Why conditional rendering is essential for dynamic applications.
    • How to use modern Angular @if, @else if, and @else control flow.
    • How traditional *ngIf works in existing Angular applications.
    • How to handle multiple conditions.
    • How to combine conditional rendering with Signals and component state.
    • The difference between conditionally rendering an element and visually hiding it.
    • How conditional rendering works in real-world enterprise applications.
    • Authentication and role-based UI rendering patterns.
    • Performance considerations and best practices.
    • Common mistakes and interview questions.

    Introduction

    Imagine opening an online banking application.

    If you're logged in, you see:

    • Account Balance
    • Transaction History
    • Money Transfer
    • Credit Cards
    • Investments

    If you're not logged in, you see:

    text
    Please log in to continue.

    Now imagine different types of users.

    A regular customer sees:

    text
    Account Dashboard
    Money Transfer
    Transaction History

    An administrator may additionally see:

    text
    User Management
    System Configuration
    Audit Logs

    The application doesn't display every element to every user.

    Instead, it decides what to render based on the current application state.

    This concept is called Conditional Rendering.

    In Angular, conditional rendering allows the application to dynamically create different user interfaces depending on conditions such as authentication status, user role, loading state, API response, product availability, form validation, feature flags, device capabilities, and business rules.

    Modern Angular provides built-in control-flow syntax such as @if, @else if, and @else, making conditional templates easier to read and maintain.

    A Real-World Story

    Imagine you're building an e-commerce application.

    A product can have different states:

    text
    In Stock
    Low Stock
    Out of Stock
    Discontinued

    The user interface must respond differently to each state.

    If the product is available:

    text
    Add to Cart

    If the product is running low:

    text
    Only 2 left - order soon!

    If the product is unavailable:

    text
    Out of Stock

    The application may also disable or remove the purchase action.

    Conceptually:

    text
    Product State
    Conditional Rendering
    ├── In Stock
    │ └── Show "Add to Cart"
    ├── Low Stock
    │ └── Show Warning
    └── Out of Stock
    └── Show Unavailable Message

    Instead of manually manipulating the DOM, Angular allows the template to declare these conditions directly.

    What Is Conditional Rendering?

    Conditional Rendering means displaying or creating parts of the user interface only when specific conditions are satisfied.

    text
    IF user is logged in
    Show Dashboard
    ELSE
    Show Login Page

    In modern Angular, this can be written as:

    html
    @if (isLoggedIn) {
    <h2>Welcome to your Dashboard</h2>
    } @else {
    <h2>Please log in</h2>
    }

    The template automatically reacts when the condition changes.

    Why Do We Need Conditional Rendering?

    Modern applications are dynamic.

    The same screen may look completely different depending on application state.

    Application State

    What Determines the UI?

    Logged In
    Show dashboard or login
    User Role
    Show customer or admin features
    API Status
    Show loading, content, empty, or error

    Without conditional rendering, developers would need to manually create elements, remove elements, modify DOM nodes, track visibility, and synchronize the UI with application state.

    Angular handles this declaratively. You define what should appear, and Angular manages the rendering.

    Modern Angular Conditional Rendering with @if

    Modern Angular provides built-in control flow.

    Basic syntax:

    html
    @if (condition) {
    <!-- Content -->
    }

    Example component:

    typescript
    export class ProductComponent {
    isAvailable = true;
    }

    Template:

    html
    @if (isAvailable) {
    <button>Add to Cart</button>
    }

    If isAvailable is true, Angular renders Add to Cart. If it is false, the button isn't rendered by that conditional block.

    How @if Works

    Conceptually:

    text
    Component State
    isAvailable
    @if Condition
    ┌───┴────┐
    │ │
    true false
    │ │
    ▼ ▼
    Render Don't Render
    Content Content

    Angular evaluates the expression and renders the appropriate template content.

    Using @else

    Often, you need an alternative UI.

    html
    @if (isLoggedIn) {
    <h2>Welcome back!</h2>
    <button>
    Logout
    </button>
    } @else {
    <h2>Please log in</h2>
    <button>
    Login
    </button>
    }

    The result depends entirely on application state.

    Using @else if

    Real applications often have more than two states.

    Suppose a customer's account has three possible states:

    text
    ACTIVE
    SUSPENDED
    CLOSED
    html
    @if (accountStatus === 'ACTIVE') {
    <p>Your account is active.</p>
    } @else if (accountStatus === 'SUSPENDED') {
    <p>Your account is temporarily suspended.</p>
    } @else {
    <p>Your account is closed.</p>
    }

    This makes multi-condition rendering much easier to understand.

    Real-World Example: Product Availability

    Component:

    typescript
    export class ProductComponent {
    product = {
    name: 'Laptop',
    stock: 2
    };
    }

    Template:

    html
    <h2>{{ product.name }}</h2>
    @if (product.stock > 5) {
    <p>In Stock</p>
    <button>Add to Cart</button>
    } @else if (product.stock > 0) {
    <p>Only {{ product.stock }} left!</p>
    <button>Add to Cart</button>
    } @else {
    <p>Out of Stock</p>
    <button disabled>Unavailable</button>
    }

    Now the UI automatically adapts to inventory state.

    Traditional Conditional Rendering with *ngIf

    Although modern Angular provides @if, you'll frequently encounter *ngIf in existing enterprise applications.

    html
    <div *ngIf="isLoggedIn">
    Welcome back!
    </div>

    Historically, an alternative block could be implemented using ng-template.

    html
    <div *ngIf="isLoggedIn; else loginTemplate">
    Welcome back!
    </div>
    <ng-template #loginTemplate>
    Please log in.
    </ng-template>

    For modern Angular projects, built-in control flow often provides cleaner syntax.

    Modern @if vs Traditional *ngIf

    Feature@if*ngIf
    StyleBuilt-in control flowStructural directive
    Modern AngularPreferred in many new applicationsCommon in existing applications
    Else syntax@elseng-template or related patterns
    Else-if syntax@else ifUsually nested conditions
    ReadabilityOften simplerFamiliar in legacy codebases

    The important point isn't to treat older syntax as incorrect. Instead, understand the evolution of Angular templates.

    Conditional Rendering with Component State

    Conditional rendering usually depends on component state.

    typescript
    export class DashboardComponent {
    isLoading = true;
    hasError = false;
    data: unknown = null;
    }
    html
    @if (isLoading) {
    <p>Loading data...</p>
    } @else if (hasError) {
    <p>Unable to load data.</p>
    } @else {
    <p>Data loaded successfully.</p>
    }

    This pattern is extremely common in applications that communicate with APIs.

    Real-World API Rendering Pattern

    When an application calls an API, the UI may need to represent several states.

    text
    API Request
    Loading
    ├── Success
    │ ├── Has Data -> Show Data
    │ └── No Data -> Empty State
    └── Failure -> Error Message

    A template might conceptually implement:

    html
    @if (isLoading) {
    <app-loader />
    } @else if (errorMessage) {
    <app-error-message />
    } @else if (products.length === 0) {
    <app-empty-state />
    } @else {
    <app-product-list />
    }

    This creates a much better user experience than showing a blank screen.

    The Four Important UI States

    Professional applications should often consider at least these states:

    text
    1. Loading
    2. Success
    3. Empty
    4. Error

    Ignoring these states is a common beginner mistake. Enterprise applications should design for all expected outcomes.

    Conditional Rendering with Signals

    Modern Angular applications may manage reactive state using Signals.

    typescript
    import {
    Component,
    signal
    } from '@angular/core';
    @Component({
    selector: 'app-dashboard',
    templateUrl: './dashboard.component.html'
    })
    export class DashboardComponent {
    isLoggedIn = signal(false);
    }

    Template:

    html
    @if (isLoggedIn()) {
    <h2>Dashboard</h2>
    } @else {
    <h2>Please log in</h2>
    }

    When the signal changes, Angular updates the relevant UI.

    Conditional Rendering vs Hiding Elements

    This distinction is extremely important.

    Conditional rendering:

    html
    @if (isVisible) {
    <app-dashboard />
    }

    CSS hiding:

    html
    <div [hidden]="!isVisible">
    Dashboard
    </div>
    text
    Conditional Rendering
    Condition = false -> Element Not Rendered
    Visual Hiding
    Condition = false -> Element Exists -> Hidden Visually

    These approaches have different implications.

    When Should You Conditionally Render?

    • The component isn't needed.
    • The UI depends strongly on application state.
    • Creating the component unnecessarily would waste resources.
    • You want lifecycle creation and destruction to follow visibility.

    Examples include dialogs, expensive charts, authenticated sections, conditional forms, and feature-specific components.

    When Might You Hide Instead?

    • You need to preserve an existing DOM element.
    • You want to preserve certain UI state.
    • Toggling visibility is frequent and recreation is undesirable.

    This decision should be based on actual application requirements rather than habit.

    Real-Time Example: Authentication

    typescript
    export class AppComponent {
    isAuthenticated = false;
    }
    html
    @if (isAuthenticated) {
    <app-dashboard />
    } @else {
    <app-login />
    }

    This is one of the most common uses of conditional rendering.

    Role-Based Conditional Rendering

    Suppose your application has ADMIN, MANAGER, and USER roles.

    html
    @if (userRole === 'ADMIN') {
    <button>
    Manage Users
    </button>
    }

    Conditional rendering controls what users see. It does not determine what users are authorized to do.

    Never rely on conditional rendering as your only security mechanism.

    Enterprise Role-Based Architecture

    Role-Based Architecture

    Frontend Improves UX, Backend Enforces Security

    Angular Frontend

    Uses conditional UI to show relevant controls.

    Backend API

    Performs the actual authorization check.

    The frontend improves usability. The backend provides security. Both are necessary, but they serve different purposes.

    Real-World Example: Feature Flags

    Large organizations frequently release features gradually.

    typescript
    export class DashboardComponent {
    newPaymentFeatureEnabled = true;
    }
    html
    @if (newPaymentFeatureEnabled) {
    <app-new-payment-dashboard />
    } @else {
    <app-classic-payment-dashboard />
    }

    In production, the feature flag may come from remote configuration, backend APIs, environment configuration, or a feature management service.

    Real-World Example: Subscription Plans

    Imagine a SaaS platform with FREE, PRO, and ENTERPRISE plans.

    html
    @if (plan === 'ENTERPRISE') {
    <app-enterprise-dashboard />
    } @else if (plan === 'PRO') {
    <app-pro-dashboard />
    } @else {
    <app-free-dashboard />
    }

    Conditional rendering makes it possible to customize experiences for different customer segments.

    Avoid Complex Conditions in Templates

    Avoid writing overly complex logic directly in templates.

    html
    @if (
    user &&
    user.role === 'ADMIN' &&
    user.active &&
    subscription.valid &&
    permissions.includes('MANAGE_USERS')
    ) {
    <button>Manage Users</button>
    }

    A better approach may be to calculate the state in the component:

    typescript
    get canManageUsers(): boolean {
    return (
    this.user?.role === 'ADMIN' &&
    this.user.active &&
    this.subscription.valid &&
    this.permissions.includes(
    'MANAGE_USERS'
    )
    );
    }

    Template:

    html
    @if (canManageUsers) {
    <button>
    Manage Users
    </button>
    }

    For frequently evaluated or computationally expensive derived state, consider computed Signals rather than complex template methods.

    Conditional Rendering Architecture

    A scalable Angular application often follows this pattern:

    text
    Backend API
    Service
    Application State
    Component
    Conditional Rendering
    ├── Loading
    ├── Success
    │ ├── Has Data
    │ └── Empty
    └── Error

    The template doesn't decide business rules independently. Instead, it renders the state provided by the application.

    Performance Considerations

    Conditional rendering can affect performance because components may be created and destroyed as conditions change.

    text
    Condition True
    Component Created
    Initialization Runs
    Condition False
    Component Destroyed

    If a component is expensive to initialize and the condition changes frequently, repeated creation may have a cost.

    Before optimizing, measure the actual performance impact. Premature optimization can create unnecessary complexity.

    Best Practices

    • Prefer modern built-in control flow such as @if for new Angular code where appropriate.
    • Understand *ngIf because it's common in existing applications.
    • Keep conditional expressions simple and readable.
    • Design loading, success, empty, and error states.
    • Don't use conditional rendering as a replacement for backend authorization.
    • Extract complicated business conditions from templates.
    • Use Signals or other appropriate state-management techniques for reactive application state.
    • Consider component lifecycle costs when conditionally rendering expensive components.
    • Use semantic and accessible UI for every state.
    • Avoid deeply nested conditional blocks when a clearer component structure is possible.

    Common Pitfalls

    Using Conditional UI as Security

    Hidden buttons do not secure APIs. Backend authorization is mandatory.

    Ignoring Loading States

    A blank screen during an API request is a poor user experience. Show a loading indicator.

    Ignoring Empty States

    A successful API response may contain no data. Show an empty state instead of treating it as an error.

    Deeply Nested Conditions

    Too many nested conditions make templates difficult to understand. Consider extracting dedicated components.

    Mixing Business Logic with Rendering Logic

    The template should primarily answer: "What should the user see?" Complex business rules should generally be calculated elsewhere.

    Common Misconceptions

    Misconception

    Conditional rendering simply hides an element.

    Reality

    True conditional rendering controls whether template content is rendered. CSS-based hiding may leave the element in the DOM.

    Misconception

    *ngIf is the only way to conditionally render content in Angular.

    Reality

    Modern Angular provides built-in control flow using @if, @else if, and @else.

    Misconception

    If an Admin button isn't rendered, the application is secure.

    Reality

    Frontend rendering only affects the user interface. Backend APIs must independently enforce authorization.

    Misconception

    Every condition should be written directly inside the template.

    Reality

    Complex conditions are often clearer when represented as well-named component state or derived reactive state.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    7 questions
    1BeginnerQuestionWhat is Conditional Rendering in Angular?+

    Answer

    Conditional Rendering is the process of rendering different template content based on application state or logical conditions. Modern Angular supports built-in control flow using @if, @else if, and @else.
    2IntermediateQuestionWhat is the difference between @if and *ngIf?+

    Answer

    @if is modern Angular's built-in control-flow syntax. *ngIf is the traditional structural directive used extensively in older and existing Angular applications.
    3IntermediateQuestionWhat is the difference between conditional rendering and [hidden]?+

    Answer

    Conditional rendering determines whether content is rendered as part of the view. [hidden] typically keeps the element in the DOM while changing its visual visibility.
    4AdvancedQuestionCan Conditional Rendering be used for authorization?+

    Answer

    It can improve the UI by hiding controls that users should not normally access, but it must never be the primary security mechanism. Authorization must be enforced by backend services.
    5IntermediateQuestionHow would you handle API states in an Angular template?+

    Answer

    A robust UI typically considers loading, success with data, success with no data, and error states. Conditional rendering can display the appropriate component or message for each state.
    6AdvancedQuestionHow do Signals work with conditional rendering?+

    Answer

    A Signal can represent reactive application state. When a Signal used by a template changes, Angular can update the relevant UI based on the new state.
    7AdvancedQuestionWhen might conditional rendering affect performance?+

    Answer

    When conditions frequently create and destroy expensive components, repeated initialization and cleanup may introduce overhead. Measure real performance before optimizing.

    Summary

    Angular Conditional Rendering allows the user interface to adapt dynamically to application state.

    The fundamental architecture is simple:

    text
    Application State
    Condition Evaluated
    ┌───┴────┐
    ▼ ▼
    True False
    │ │
    ▼ ▼
    UI A UI B

    In real enterprise applications, conditional rendering becomes much more powerful when it reflects authentication, API state, feature flags, and role-specific experiences.

    The most important lesson is that conditional rendering should reflect well-designed application state rather than contain complicated business logic directly inside the template.

    By combining clean state management with Angular's modern @if control flow, you can create interfaces that are dynamic, maintainable, performant, and easy for users to understand.

    In the next lesson, Angular Lists, you'll learn how to efficiently render collections of data using modern Angular @for, understand the importance of tracking items, compare it with traditional *ngFor, and explore how professional applications handle large datasets, pagination, virtual scrolling, and list performance.

    Ready to mark this lesson complete?Track your journey across the entire course.