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.
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@elsecontrol flow. - How traditional
*ngIfworks 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:
Please log in to continue.
Now imagine different types of users.
A regular customer sees:
Account DashboardMoney TransferTransaction History
An administrator may additionally see:
User ManagementSystem ConfigurationAudit 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:
In StockLow StockOut of StockDiscontinued
The user interface must respond differently to each state.
If the product is available:
Add to Cart
If the product is running low:
Only 2 left - order soon!
If the product is unavailable:
Out of Stock
The application may also disable or remove the purchase action.
Conceptually:
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.
IF user is logged inShow DashboardELSEShow Login Page
In modern Angular, this can be written as:
@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?
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:
@if (condition) {<!-- Content -->}
Example component:
export class ProductComponent {isAvailable = true;}
Template:
@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:
Component State│▼isAvailable│▼@if Condition│┌───┴────┐│ │true false│ │▼ ▼Render Don't RenderContent Content
Angular evaluates the expression and renders the appropriate template content.
Using @else
Often, you need an alternative UI.
@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:
ACTIVESUSPENDEDCLOSED
@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:
export class ProductComponent {product = {name: 'Laptop',stock: 2};}
Template:
<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.
<div *ngIf="isLoggedIn">Welcome back!</div>
Historically, an alternative block could be implemented using ng-template.
<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 |
|---|---|---|
| Style | Built-in control flow | Structural directive |
| Modern Angular | Preferred in many new applications | Common in existing applications |
| Else syntax | @else | ng-template or related patterns |
| Else-if syntax | @else if | Usually nested conditions |
| Readability | Often simpler | Familiar 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.
export class DashboardComponent {isLoading = true;hasError = false;data: unknown = null;}
@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.
API Request│▼Loading│├── Success│ ├── Has Data -> Show Data│ └── No Data -> Empty State│└── Failure -> Error Message
A template might conceptually implement:
@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:
1. Loading2. Success3. Empty4. 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.
import {Component,signal} from '@angular/core';@Component({selector: 'app-dashboard',templateUrl: './dashboard.component.html'})export class DashboardComponent {isLoggedIn = signal(false);}
Template:
@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:
@if (isVisible) {<app-dashboard />}
CSS hiding:
<div [hidden]="!isVisible">Dashboard</div>
Conditional RenderingCondition = false -> Element Not RenderedVisual HidingCondition = 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
export class AppComponent {isAuthenticated = false;}
@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.
@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.
export class DashboardComponent {newPaymentFeatureEnabled = true;}
@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.
@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.
@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:
get canManageUsers(): boolean {return (this.user?.role === 'ADMIN' &&this.user.active &&this.subscription.valid &&this.permissions.includes('MANAGE_USERS'));}
Template:
@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:
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.
Condition True│▼Component Created│▼Initialization RunsCondition 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
@iffor new Angular code where appropriate. - Understand
*ngIfbecause 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.
1BeginnerQuestionWhat is Conditional Rendering in Angular?+
Answer
@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
[hidden] typically keeps the element in the DOM while changing its visual visibility.4AdvancedQuestionCan Conditional Rendering be used for authorization?+
Answer
5IntermediateQuestionHow would you handle API states in an Angular template?+
Answer
6AdvancedQuestionHow do Signals work with conditional rendering?+
Answer
7AdvancedQuestionWhen might conditional rendering affect performance?+
Answer
Summary
Angular Conditional Rendering allows the user interface to adapt dynamically to application state.
The fundamental architecture is simple:
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.