ngIf, Else, Then

In this weeks blog I will be taking a look at Agular’s NgIf, Else, and Then directives and the different syntaxes that can be used to better deal with conditionals and asynchronous objects. The ngIf directive when placed on a component will hide or show the details of that component or element based on the expression that you pass it to be evaluated. If the expression is evaluated to true, Angular will add  your DOM nodes and mount or remount your components. Another reason to use ngIf is the availability to invoke relevant lifecycle hooks such as ngOnInit and ngOnDestroy. The most standard use of ngIf is to provide a “true or false” type expression based on an evaluation. A common example of the standard use of ngIf would include:

@Component( {

Selector: ‘app’


Welcome back!

This basic use of ngIf check to see if the user is logged in and if so, Welcome back is displayed.

The next form that can be used is *ngIf and Else. The else statement makes it easy to provide a strategy that Angular can follow if the first *ngIf expression fails or is invalid.

<div *ngIf = “isLoggedIn; else loggedOut”

Welcome back!


<ng-template #loggedOut>

Please Login


Here *ngIf is used to see if the user is logged in else it used the local reference of #loggedOut to tell the user to login.


One of the final variations of the ngIf directed is *ngIf, Then and Else. Using then alongside ngIf moves out ignition *ngIf template outside the element we’re binding it to. This allows use to dynamically change the template reference to then, swapping ng template as we go.



*ngIf= “isLoggedIn; then loggedIn; else loggedOut”>



In conclusion, ngIf is a versatile directive that can have many use cases apart from the code above and is a great way of providing If, Else, Then statements to your Angular application.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s