Angular’s NgIf, Else, Then – Explained

Using the ngIf directive allows us to simply toggle content based on a conditional. But is it as simple as we think? Not quite, the directive has a heap of helpful syntaxes that can help us deal with conditionals far better, and also asynchronous objects coming from perhaps an Observable.
Let’s explore the ins and outs of ngIf, and how we can utilise (the right way) in our Angular apps.

Table of contents

Angular’s ngIf
Standard *ngIf in Angular
*ngIf and Else
ngIf and ng-template
*ngIf, Then and Else

*ngIf, Observables and Async Pipe

Angular’s ngIf
Placing the ngIf directive on a component, or element, will in fact hide or show that element based on the expression you pass it to be evaluated. Once evaluated, Angular will simply add or remove your DOM nodes, mount or remount your components, from the DOM – as the expression changes (if it ever does, that’s up to you).

When using an ngIf on a component, this will in turn invoke relevant lifecycle hooks such as ngOnInit, ngOnDestroy, and so forth.

The basic syntax of the ngIf directive is simple and effective, all we need to do it prefix it with an asterisk (*) and add it anywhere inside our template. We’ll cover why we use the asterisk syntax, shortly.
Standard *ngIf in Angular
There are four main ways we can use ngIf, so let’s start by exploring the most basic use case:
@Component({
selector: ‘app’,
template: `