Conditional Rendering with ngIf in Angular

kavindukarunasena

Kavindu Karunasena

Posted on April 20, 2024

Conditional Rendering with ngIf in Angular

In Angular applications, dynamic content based on data or user interactions is essential. The ngIf structural directive provides a powerful way to conditionally include or exclude elements from the template, ensuring a seamless user experience.

Understanding ngIf

  • Structural Directive: ngIf modifies the DOM structure by adding or removing elements based on a condition.
  • Expression Binding: It takes an expression as input, typically a boolean value or one that evaluates to truthy or falsy.
  • Conditional Rendering: When the expression is true, the element and its content are displayed. If it's false, they're removed from the DOM, optimizing performance.
<div *ngIf="isLoggedIn">
  Welcome back!
</div>
Enter fullscreen mode Exit fullscreen mode
  • The *ngIf directive is placed on a div.
  • The expression isLoggedIn controls the visibility.
  • If isLoggedIn is true, the welcome message with the username is displayed.
  • Otherwise, the div and its content are hidden from the user.

example:

<div>
  <p *ngIf="value">The value is true.</p>
  <p *ngIf="!value">The value is false.</p>
</div>

Enter fullscreen mode Exit fullscreen mode

In above code if the value is true, only display "The value is true". Otherwise display "The value is false."

💖 💪 🙅 🚩
kavindukarunasena
Kavindu Karunasena

Posted on April 20, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related