Angular’s If statement (and Else)

In Angular, you can use *ngIf to conditionally add an element in the DOM only when a condition is true.

This is different from showing an element when a condition is true because with *ngIf, it will not exist at all in the DOM unless the condition is true. Here is a sample (using square brackets from html)

[div *ngIf="showDiv"] This is the inner html / inner text in the div
[/div]

The ‘*’ must be there.
The ‘*’ means it is a Structural Directive that will change the structure of the DOM.
The value you of ‘showDiv’ must be a boolean value.
The ‘showDiv’ in this case is a property in my ts file. I could also bind to a showDiv function in my ts file just by adding parens as follows:

[div *ngIf="showDiv()"] This is the inner html / inner text in the div
[/div]

What if you want to do an ‘else’? It’s a little messier. You must add a ng-template and name it like this (the name doesn’t really matter what you put).

[ng-template #myElseSection]
  [p] Paragraph to show when else is hit. [/p]
[/ng-template]

Now you else can work like this:

[div *ngIf="showDiv(); else myElseSection"] This is the inner html / inner text in the div
[/div]

[ng-template #myElseSection]
  [p] Paragraph to show when else is hit. [/p]
[/ng-template]

So the first div is shown when the ‘if’ is true, and the paragraph in #myElseSection is shown when the else is true.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

w

Connecting to %s