Using ngIf in Angular

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 *ngIf and its purpose
  • Basic usage and syntax
  • Combining *ngIf with else for conditional alternatives
  • Using *ngIf with then templates
  • Nesting and combining multiple *ngIf conditions
  • 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>
  • condition is 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: `
&lt;p *ngIf="isLoggedIn"&gt;Welcome back!&lt;/p&gt;
&lt;p *ngIf="!isLoggedIn"&gt;Please log in to continue.&lt;/p&gt;
` }) export class LoginStatusComponent { isLoggedIn = true; // Change to false to test the else condition }
  • When isLoggedIn is true, the first paragraph is displayed
  • When isLoggedIn is false, 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-template defines a reusable template
  • #loginPrompt is a template reference
  • else loginPrompt renders the template when the condition is false

Example: User Authentication Message

@Component({
  selector: 'app-auth-message',
  template: `
&lt;p *ngIf="isLoggedIn; else loginMessage"&gt;Hello, {{ username }}!&lt;/p&gt;
&lt;ng-template #loginMessage&gt;
  &lt;p&gt;You need to log in to access this feature.&lt;/p&gt;
&lt;/ng-template&gt;
` }) 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>
  • then specifies the template when condition is true
  • else specifies the template when condition is false
  • ng-container acts as a structural wrapper that doesn’t render additional DOM elements

Benefits of Using then and else

  • Avoids repeating *ngIf in 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: `
&lt;p *ngIf="isLoggedIn &amp;&amp; role === 'admin'"&gt;Welcome, Admin!&lt;/p&gt;
&lt;p *ngIf="isLoggedIn &amp;&amp; role === 'user'"&gt;Welcome, User!&lt;/p&gt;
&lt;p *ngIf="!isLoggedIn"&gt;Please log in to continue.&lt;/p&gt;
` }) 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 *ngIf conditions are evaluated only if the outer condition is true
  • Reduces unnecessary DOM evaluations

Performance Considerations

  1. Use *ngIf instead of CSS display: none
    • Removes elements from the DOM instead of hiding them
    • Reduces memory usage and improves performance
  2. Avoid Complex Expressions Inline
    • Compute values in the component class instead of inline in *ngIf
// Better
showAdminMessage() {
  return this.isLoggedIn && this.role === 'admin';
}
<p *ngIf="showAdminMessage()">Welcome, Admin!</p>
  • Improves readability and performance
  1. Use ng-container for Structural Wrapping
    • Avoids extra DOM nodes when using then/else

Practical Example: Dynamic Dashboard

Imagine a dashboard component that displays content based on user login and role:

@Component({
  selector: 'app-dashboard',
  template: `
&lt;ng-container *ngIf="isLoggedIn; then loggedInTemplate; else loginTemplate"&gt;&lt;/ng-container&gt;
&lt;ng-template #loggedInTemplate&gt;
  &lt;h1&gt;Dashboard&lt;/h1&gt;
  &lt;p *ngIf="role === 'admin'"&gt;Admin Panel Access&lt;/p&gt;
  &lt;p *ngIf="role === 'user'"&gt;User Panel Access&lt;/p&gt;
&lt;/ng-template&gt;
&lt;ng-template #loginTemplate&gt;
  &lt;h1&gt;Welcome&lt;/h1&gt;
  &lt;p&gt;Please log in to access your dashboard.&lt;/p&gt;
&lt;/ng-template&gt;
` }) export class DashboardComponent { isLoggedIn = true; role: 'admin' | 'user' = 'user'; }
  • Dashboard dynamically updates based on authentication and role
  • Uses *ngIf with then/else and 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">
&lt;li *ngIf="item.visible"&gt;{{ item.name }}&lt;/li&gt;
</ng-container> </ul>
  • Keeps DOM clean and avoids multiple structural directives on a single element

Best Practices for Using *ngIf

  1. Prefer *ngIf Over CSS Hiding
    • Removes unnecessary DOM nodes and improves performance
  2. Use ng-container for Non-Rendered Wrappers
    • Useful when combining then/else templates
  3. Avoid Complex Inline Expressions
    • Keep templates readable and maintainable
  4. Combine with Component Properties
    • Compute conditions in the component class instead of inline expressions
  5. Use *ngIf with Lazy Loading
    • For heavy components, conditionally render them only when necessary

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *