Angular 9|8|7 NgIf, Else, Then Quick Tutorial with Example

NgIf directive is used in dom elements to show or hides conditionally based on expressions. We are pretty much aware of this behavior which we used in the previous version of AngularJS. But it has transformed to provide more features and support for more expressions which we are going to explore. NgIf in Angular 2+…

By.

•

min read

NgIf directive is used in dom elements to show or hides conditionally based on expressions. We are pretty much aware of this behavior which we used in the previous version of AngularJS.

But it has transformed to provide more features and support for more expressions which we are going to explore.

NgIf in Angular 2+ versions can be used in the following three ways

1) *ngIf: The simple if

Using *ngIf we can provide an expression which returns boolean flag true or false to add or remove the element from DOM having *ngIf directive

...
...
export class AppComponent {
  isDone = true;
}
<div *ngIf="isDone">
  It's Done!
</div>

<!-- Negation operator-->
<div *ngIf="!isDone">
  It's Not Done!
</div>

 

2) *ngIf and Else: If statement with else

Yes, it's awesome to have the else statement with if to handle conditions. So instead of using negation(!) operator, we used earlier can be achieved using else block as shown below

<ng-container *ngIf="isDone; else elseNotDone">
  It's Done!
</ng-container>

<ng-template #elseNotDone>
  It's Not Done!
</ng-template>

ng-template is virtual tag who's content can be replaced in the container.

 

3) *ngIf, Then and Else: NgIf else redefined

Now we have a new then statement which is true when *ngIf expression is true. This is similar is simple *ngIf else but sometimes provide more flexibility.

<ng-container *ngIf="isDone;  then iAmDone; else iAmNotDone">
</ng-container>

<ng-template #iAmDone>
  It's Not Done!
</ng-template>

<ng-template #iAmNotDone>
  It's Not Done!
</ng-template>

 

Conclusion: In this article, we discussed the ways in which we can use If else conditional statements in the DOM template to conditionally handle elements.

2 responses to “Angular 9|8|7 NgIf, Else, Then Quick Tutorial with Example”

Leave a Reply

Your email address will not be published. Required fields are marked *