Angular provides powerful structural directives that allow developers to manipulate the DOM dynamically based on application state. One of the most commonly used directives is *ngIf. This directive enables conditional rendering, ensuring that elements are added to or removed from the DOM depending on a boolean expression.
In this comprehensive guide, we will cover:
- Introduction to
*ngIfand its purpose - Basic usage and syntax
- Combining
*ngIfwithelsefor conditional alternatives - Using
*ngIfwiththentemplates - Nesting and combining multiple
*ngIfconditions - Best practices and performance considerations
- Practical examples in real-world applications
What Is ngIf?
*ngIf is a structural directive in Angular. Structural directives change the structure of the DOM by adding or removing elements based on a condition.
- When the condition is true, the element is rendered
- When the condition is false, the element is removed from the DOM
This is different from CSS display: none, which hides elements but keeps them in the DOM. *ngIf completely removes the element, improving performance and clarity.
Basic Syntax
<p *ngIf="condition">This will be displayed if condition is true.</p>
conditionis a boolean property or an expression evaluated in the component class.
Example: Simple Conditional Rendering
import { Component } from '@angular/core';
@Component({
selector: 'app-login-status',
template: `
<p *ngIf="isLoggedIn">Welcome back!</p>
<p *ngIf="!isLoggedIn">Please log in to continue.</p>
`
})
export class LoginStatusComponent {
isLoggedIn = true; // Change to false to test the else condition
}
- When
isLoggedInistrue, the first paragraph is displayed - When
isLoggedInisfalse, the second paragraph is displayed
Using *ngIf with else
Angular allows combining *ngIf with an else clause to render an alternative template when the condition is false.
Syntax
<p *ngIf="isLoggedIn; else loginPrompt">Welcome back!</p>
<ng-template #loginPrompt>
<p>Please log in to continue.</p>
</ng-template>
ng-templatedefines a reusable template#loginPromptis a template referenceelse loginPromptrenders the template when the condition is false
Example: User Authentication Message
@Component({
selector: 'app-auth-message',
template: `
<p *ngIf="isLoggedIn; else loginMessage">Hello, {{ username }}!</p>
<ng-template #loginMessage>
<p>You need to log in to access this feature.</p>
</ng-template>
`
})
export class AuthMessageComponent {
isLoggedIn = false;
username = 'John Doe';
}
- Provides a clean way to handle conditional rendering
- Prevents duplication of template code
Using *ngIf with then Template
In addition to else, Angular provides a then clause for more readable templates, especially when using multiple alternatives.
Syntax
<ng-container *ngIf="isLoggedIn; then loggedInTemplate; else loginTemplate"></ng-container>
<ng-template #loggedInTemplate>
<p>Welcome back, {{ username }}!</p>
</ng-template>
<ng-template #loginTemplate>
<p>Please log in to continue.</p>
</ng-template>
thenspecifies the template when condition is trueelsespecifies the template when condition is falseng-containeracts as a structural wrapper that doesn’t render additional DOM elements
Benefits of Using then and else
- Avoids repeating
*ngIfin multiple places - Improves readability and maintainability
- Useful for complex UI states
Multiple Conditions with *ngIf
You can combine multiple conditions using logical operators in the *ngIf expression:
<p *ngIf="isLoggedIn && isAdmin">Welcome, admin!</p>
<p *ngIf="isLoggedIn && !isAdmin">Welcome, user!</p>
<p *ngIf="!isLoggedIn">Please log in.</p>
- Evaluates boolean expressions in real time
- Dynamically updates the DOM as conditions change
Example: Role-Based Display
@Component({
selector: 'app-role-message',
template: `
<p *ngIf="isLoggedIn && role === 'admin'">Welcome, Admin!</p>
<p *ngIf="isLoggedIn && role === 'user'">Welcome, User!</p>
<p *ngIf="!isLoggedIn">Please log in to continue.</p>
`
})
export class RoleMessageComponent {
isLoggedIn = true;
role = 'admin'; // Change to 'user' to test different roles
}
- Allows rendering dynamic content based on multiple conditions
Nesting *ngIf Directives
You can nest *ngIf directives for more complex scenarios:
<div *ngIf="isLoggedIn">
<p *ngIf="role === 'admin'">You have full access.</p>
<p *ngIf="role === 'user'">You have limited access.</p>
</div>
<div *ngIf="!isLoggedIn">
<p>Please log in.</p>
</div>
- Inner
*ngIfconditions are evaluated only if the outer condition is true - Reduces unnecessary DOM evaluations
Performance Considerations
- Use
*ngIfinstead of CSSdisplay: none- Removes elements from the DOM instead of hiding them
- Reduces memory usage and improves performance
- Avoid Complex Expressions Inline
- Compute values in the component class instead of inline in
*ngIf
- Compute values in the component class instead of inline in
// Better
showAdminMessage() {
return this.isLoggedIn && this.role === 'admin';
}
<p *ngIf="showAdminMessage()">Welcome, Admin!</p>
- Improves readability and performance
- Use
ng-containerfor Structural Wrapping- Avoids extra DOM nodes when using
then/else
- Avoids extra DOM nodes when using
Practical Example: Dynamic Dashboard
Imagine a dashboard component that displays content based on user login and role:
@Component({
selector: 'app-dashboard',
template: `
<ng-container *ngIf="isLoggedIn; then loggedInTemplate; else loginTemplate"></ng-container>
<ng-template #loggedInTemplate>
<h1>Dashboard</h1>
<p *ngIf="role === 'admin'">Admin Panel Access</p>
<p *ngIf="role === 'user'">User Panel Access</p>
</ng-template>
<ng-template #loginTemplate>
<h1>Welcome</h1>
<p>Please log in to access your dashboard.</p>
</ng-template>
`
})
export class DashboardComponent {
isLoggedIn = true;
role: 'admin' | 'user' = 'user';
}
- Dashboard dynamically updates based on authentication and role
- Uses
*ngIfwiththen/elseand nested conditions - Avoids clutter in the template
Combining *ngIf with *ngFor
*ngIf can also be combined with *ngFor for dynamic lists:
<ul>
<li *ngFor="let item of items" *ngIf="item.visible">{{ item.name }}</li>
</ul>
Note: Angular recommends using ng-container to combine directives:
<ul>
<ng-container *ngFor="let item of items">
<li *ngIf="item.visible">{{ item.name }}</li>
</ng-container>
</ul>
- Keeps DOM clean and avoids multiple structural directives on a single element
Best Practices for Using *ngIf
- Prefer
*ngIfOver CSS Hiding- Removes unnecessary DOM nodes and improves performance
- Use
ng-containerfor Non-Rendered Wrappers- Useful when combining
then/elsetemplates
- Useful when combining
- Avoid Complex Inline Expressions
- Keep templates readable and maintainable
- Combine with Component Properties
- Compute conditions in the component class instead of inline expressions
- Use
*ngIfwith Lazy Loading- For heavy components, conditionally render them only when necessary
Leave a Reply