How to use ngif in Angular

Fuji Nguyen
Knowledge Pills
Published in
1 min readDec 17, 2022

--

The ngIf directive in Angular allows you to conditionally include or exclude an element from the DOM based on a boolean expression. Here's an example of how you can use ngIf in a template:

<div *ngIf="showElement">
This element will only be displayed if the "showElement" variable is truthy.
</div>

You can also use ngIf with an else clause to specify a template to display if the boolean expression is false:

<div *ngIf="showElement; else otherTemplate">
This element will only be displayed if the "showElement" variable is truthy.
</div>
<ng-template #otherTemplate>
This element will be displayed if the "showElement" variable is falsy.
</ng-template>

In the component class, you can bind the value of the showElement variable to a property in the component:

export class MyComponent {
showElement = true;
}

You can also use an expression in the ngIf directive to evaluate a more complex boolean condition:

<div *ngIf="user.isAdmin || user.isModerator">
This element will be displayed if the "isAdmin" or "isModerator" properties of the "user" object are truthy.
</div>

For more information about the ngIf directive, you can refer to the Angular documentation.

--

--

Fuji Nguyen
Knowledge Pills

DX Advocate, OpenSource Contributor, Pickleball Player - Improves software dev experience, contributes to opensource projects, and plays pickleball for leisure.