How to use *ngIf else? - learning conditional structural directives

NgIf - Powerful conditional structural directive

It is a structural directive that conditionally renders a template in the DOM based on some expression coerced to boolean. The ngIf directives can be explained as follows:

  • If the expression evaluates to true, Angular renders the template provided in a then clause and when the expression evaluates to false or null, it renders the element in the else clause.
  • The default value for the else block is blank. 
  • It takes a boolean expression. On the basis of the value of this expression, it removes or adds the element in the DOM. 
  • The ngIf element doesn't hide or show elements with CSS. It adds or removes the element completely from DOM. 
  • NgIf removes or adds element based on the boolean value. If the value is false, it removes the element from DOM, detaches it's all DOM events, detaches component from Angular change detection, and destroys it completely.
  • There is a difference between hiding and removing the element. During hiding, the element remains in the DOM, keeps listening to events, Angular keeps on checking element for change detection. Although invisible, it keeps tie to the resources. Performance and memory can degrade due to this. So it's better to remove the element than hiding it. 
  • Avoiding “Cannot read property of undefined” errors using ngIf.
This is the shorthand syntax for the *ngIf directive:
<div *ngIf="condition">Template will render if the condition is true.</div>

The same above statement can be written as follow in expanded form

The *ngIf translates to <ng-template> wrapped around the host element as below. In the statement, there is no else block. The ngIf moves to <ng-template> where it acts as property binding [ngIf]. The div which is present will render if the condition is true.

<ng-template [ngIf]="condition">
<div>Template will render if the condition is true.</div>

With an else block:

<div *ngIf="condition; else elseBlock">Template will render if the condition is true.</div>
<ng-template #elseBlock> This will render if the condition is false.</ng-template>

With else and then block both:

<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>Template will render if the condition is true.</div>
<ng-template #elseBlock> This will render if the condition is false.</ng-template>

Significance of Asterisk*

The asterisk is a convenience notation for Angular which is used with structural directives. Angular desugars this notation into a <ng-template> which surrounds host element as well as its descendants.

Note: Only one structural directive can be applied to the host element. But we can apply many attribute directive at the same host element.