Introduction
In this article, we will see *ngIf concept in Angular and its example with simple code and definition.
*ngIf (Structural Directive )
ngIf works based on the condition which is similar to "IF ELSE" statement. We know how the if else condition works in general. If the given statement in IF condition is true then that block will be executed, if the condition is false then ELSE block will be executed.
- Open terminal by pressing ctrl+` if you are using VS Code, (you can use any code editor of your choice)
- Create a component by typing the command : ng g c ComponentName.
- We will start by creating a simple button to switch between conditions
In app.component.html add the following code,
<button mat-raised-button (click)="getTrue()" color="primary">TRUE</button>
<button mat-raised-button (click)="getFalse()" color="warn">FALSE</button>
This will add 2 buttons TRUE and FALSE. Here I have used Mat buttons, you have to import Angular MatButtonModule to use Material buttons.
Add the MatButtonModule in app.module.ts,
import {MatButtonModule} from '@angular/material/button';
@NgModule({
exports: [
MatButtonModule,
]
})
Now let us create <div> tag and specify the conditions for ngIf:
In app.component.html add the following code,
<div *ngIf="condition; else falseCondition">
You have selected: <h2>"True"</h2>
</div>
<ng-template #falseCondition>
You have selected: <h2>"False"</h2>
</ng-template>
In app.component.ts add the following code,
condition: boolean;
getTrue() {
this.condition = true;
}
getFalse() {
this.condition = false;
}
Now after adding all the codes and conditions run the code by typing ng serve. By default it takes port 4200,
You can change this by adding few codes like ng serve --port 4201, this will run application on port number 4201.
Here I have not mentioned default condition for if. You can also specify default condiion for the if statements and then change the conditions based on the actions.
I have created a template reference #falseCondition in <ng-template> as else block. If the condition in <div> tag turns false then the template reference which is declared as else condition will be executed i.e,. the #falseCondition will be executed. I have created 2 user defined methods getTrue() and getFalse() for getting the conditions wheather it is true or false inside the <buttons> tag. Apart from ngIf we have ngIfThen, ngIfElse directives also which are write-only property, ngIfThen renders the template when the condition return true and ngIfElse renders the template when the condition return false.
Summary
This explains the simple working and usage of *ngIf (Structural Directive) in Angular. *ngIf physically removes element subtree, so it does not consume resources and memory which in turn results into better performance.
Hope this article is helpful for you to understand about Angular *ngIf Structural directive.
Thank You!