Angular 2+ NgIf, NgIf Else and NgIf Else Then 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+ 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


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-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.


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.

Thanks for visiting :) Let me know if you have some suggestions or feedback for this post in the comment section. Looking for any tutorial or demo on FreakyJolly, just drop me a message here

Leave a Reply

Notify of