Conditional Rendering with ngIf in Angular

Kavindu Karunasena
1 min readApr 20, 2024

--

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>
  • 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>

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

--

--

No responses yet