Angular 10 Tutorial - ngIf Directive
In this tutorial, we will learn about the ngIf Directive in Angular 10. The ngIf Directive is used to add or remove HTML elements according to the expression. The expression must return a Boolean value. If the expression is false, then the element is removed; otherwise, the element is inserted.
Using ngIf Directive in Angular 10
So, let's see how we can use the ngIf Directive in Angular 10. So, switch to the project.
Let's open the app.component.html file and here, just add a paragraph:
<p>Your age is higher than 18.</p>
Now, go to the app.component.ts file and here, create a property:
age = 19;
Now, let's add the ngIf to the paragraph:
<p *ngIf="age>18">Your age is higher than 18.</p>
Now, let's check it. You can see here the text is showing. If we change the age, let's say age = 17, now you can see here the text is not showing. Because this condition is false. If this condition will be true, then this paragraph will be rendered; otherwise, not.
Using the Else Part of ngIf
Now, let's see the else part of ngIf:
<ng-template #elseBlock>
<p>Your age is lower than 18 </p>
</ng-template>
Add here the reference variable identifier and now add here *ngIf="age>18; else elseBlock".
Now, let's check it. So, switch to the browser and here you can see the else block text. Because the age is less than 18. If I change the age, now you can see this.
Another Way to Use ngIf
Now, let's see another way to use the ngIf:
<div *ngIf="age>18; then thenBlock; else elseBlock"></div>
<ng-template #thenBlock>
<p>Your age is higher than 18 </p>
</ng-template>
<ng-template #thenBlock>
<p>Your age is lower than 18 </p>
</ng-template>
Alright, now let's check it. So, switch to the browser and here you can see this. If we change the age, let's say age is 16, now save the file and here you can see this message. So, in this way, you can use ngIf Directives in Angular 10.