*ngIf Directive in Angular
The *ngIf
directive in Angular is used to conditionally include or exclude elements from the DOM based on an expression. This tutorial covers the basics of the *ngIf
directive and how to use it effectively in your Angular applications.
What is the *ngIf Directive?
The *ngIf
directive allows you to conditionally include or exclude elements from the DOM based on the truthiness of an expression. When the expression evaluates to true, the element is included in the DOM; otherwise, it is excluded.
Basic Syntax of *ngIf
The basic syntax for the *ngIf
directive is to prefix an element with *ngIf
followed by an expression:
<div *ngIf="isVisible">This is conditionally visible</div>
export class AppComponent {
isVisible = true;
}
Using Else Clause with *ngIf
You can use the else
clause with *ngIf
to display an alternative template when the expression evaluates to false:
<ng-template #elseBlock>This is the else block</ng-template>
<div *ngIf="isVisible; else elseBlock">This is conditionally visible</div>
export class AppComponent {
isVisible = false;
}
Using Then and Else Clauses with *ngIf
You can use both then
and else
clauses with *ngIf
to display different templates for true and false conditions:
<ng-template #thenBlock>This is the then block</ng-template>
<ng-template #elseBlock>This is the else block</ng-template>
<div *ngIf="isVisible; then thenBlock; else elseBlock"></div>
export class AppComponent {
isVisible = true;
}
Combining *ngIf with ng-container
You can use ng-container
to group multiple elements under a single *ngIf
directive without adding extra nodes to the DOM:
<ng-container *ngIf="isVisible">
<p>This is visible</p>
<p>This is also visible</p>
</ng-container>
export class AppComponent {
isVisible = true;
}
Key Points
- The
*ngIf
directive conditionally includes or excludes elements from the DOM based on an expression. - Use the
else
clause with*ngIf
to display an alternative template when the expression evaluates to false. - Use both
then
andelse
clauses with*ngIf
to display different templates for true and false conditions. - Use
ng-container
to group multiple elements under a single*ngIf
directive without adding extra nodes to the DOM.
Conclusion
The *ngIf
directive is a powerful tool for conditionally including or excluding elements from the DOM in Angular. By understanding and using the *ngIf
directive effectively, you can create more dynamic and flexible Angular applications. Happy coding!