We discovered the Angular ngFor directive before, and it’s time to discover another structural directive in Angular which is ngIf directive.

If worked before with AngularJS, you surely have used ng-if directive. The concept is the same for the two frameworks. We are handling DOM Elements either by adding HTML elements or removing them.

NgIf Directive

ngIf syntax example

The ngIf code example is more than simple. It consists only of putting a boolean value in the ngIf directive.

<div *ngIf="isLoggedIn">Welcome my friend</div>

If the value of the display boolean variable is true you will see in the IHM “Welcome my friend”. In the other case ( display is false ) the div element won’t be created at all.

Angular ngIf else syntax ( with example )

You may ask what to do if you have an else case (the treatment to do in the opposite condition).

We can continue with the above example, and we will just add the syntax of the else block.

<div *ngIf="isLoggedIn; else loggedOut">
  Welcome my friend.
</div>

<ng-template #loggedOut>
  You are disconnected.
</ng-template>

NgIf or [hidden] ?

If you worked with Angular in the past, there is a high chance that you face the [hidden] property. It has globally the same goal of use as the *ngIf directive ( to not display a certain element in the User Interface). But, there is a small difference.

  • the *ngIf directive removes the HTML element from the DOM.
  • the [hidden] property will hide the element from being visible in the interface, But it will remain in the DOM.
<div [hidden]="!isLoggedIn">
  Welcome my friend.
</div>

Conclusion

In this article, you will find everything you need to know about ngIf directive. But if want more content, you can visit this link.

Thank you again and please help us by giving your feedback either in the comment section or by email contact@webdevtutos.com.