*ngIf in Angular with a twist

Showing and hiding content in is usually done by using the *ngIf directive:

<p *ngIf="isButtonClicked">Button is clicked!</p>

If you want to display something if the condition isn't satisfied you would probably do something like this:

<p *ngIf="isButtonClicked">Button clicked!</p>
<p *ngIf="!isButtonClicked">Button not clicked</p>

This looks a little clumsy and, also, forces you to repeat yourself. You are biding to the same property and if the name changes you will have to change it in multiple places - not a good thing to do.

A more elegant way of achieving the same thing looks can be seen below:

<p *ngIf="isButtonClicked; else buttonNotClicked">Button clicked!</p>

<ng-template #buttonNotClicked>
    <p>Button not clicked :(</p>
</ng-template>

The final result can be seen here:

ngif.gif

One added benefit is that you can handle these special cases anywhere in your file and Angular will do the rest