DEV Community

Cover image for Conditional Rendering with ngIf in Angular
Kavindu Karunasena
Kavindu Karunasena

Posted on

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!
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.


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

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."

Top comments (2)

jangelodev profile image
João Angelo

Hi Kavindu Karunasena,
Your tips are very useful.
Thanks for sharing.

kavindukarunasena profile image
Kavindu Karunasena • Edited

Thanks, Glad you found the tips helpful.