Angular Built-in Directives: ngIf

In the last section of this Angular tutorial, we highlighted ngFor. In this post, we will discuss ngIf.

Same as *ngFor, *ngIf is also a structural directive. It is used as a conditional statement to hide or show a specific DOM element. So, what we are gonna do is use ngIf to show or hide the list of stock markets we created earlier.

First, let’s look at it in code.

This basically tells that the list of stock markets won’t be shown in the output. Now let’s try to enhance our *ngIf statement.

In stocks.component.ts, create a boolean variable named ‘showStockMarket’. This determines our *ngIf statement to hide or show the stock market list instead of hardcoding the value as shown in the previous image.   

Now let’s add out ngIf statement in the @Component decorator.

You can also use other ways of conditional statements for ngIf. Let’s try using the length of stockMarket array to determine whether to show or hide our list.

  • First we need to determine the length of stockMarkets array.
  • Then set the condition statement whether it is equal to 5 or not.

Save your work and go to your browser again. The array does contain 5 items so the list should now appear.

And that is how ngIf for Angular works. On the next article, we are going to discuss ngSwitch.

Subscribe Now and Upgrade Your Skills Today!
Sign up now and have the latest tech tutorials delivered straight to your mailbox.

PLUS: Get exclusive member-only discounts (up to 80% OFF!!) on our top tech courses in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.