Angular - 2.23- Improve ngIf with an Else condition
In the previous lesson we covered the basic syntax of *ngIf, which is the form you will use most of the time. There is also an alternative that comes in handy when you not only have the "if" branch but also an "else" branch - for example, to display "Server was created" when the condition is true and "No server was created" otherwise. Angular lets you achieve this without duplicating *ngIf with a negated condition.
The trick is to combine *ngIf with a local reference placed on an <ng-template>. The local reference acts as a label that Angular can target. We create the fallback markup inside an ng-template and tag it: <ng-template #noServer><p>No server was created</p></ng-template>. The #noServer syntax is a template reference variable.
The complete else syntax
- Main element:
<p *ngIf="serverCreated; else noServer">Server "{{ serverName }}" was created</p>. - Fallback template:
<ng-template #noServer><p>No server was created</p></ng-template>. <ng-template>is a component-like directive shipped with Angular that lets you mark places in the markup to be rendered conditionally.
Save the file: at first sight the application displays "No server was created". As soon as we click the button and set serverCreated = true, Angular swaps the templates and we read "Server was created". The DOM only ever contains one of the two paragraphs at a time, never both - this is still the structural-directive contract.
An equivalent approach is to use two separate *ngIf directives, one with the original condition and one with its negation (*ngIf="!serverCreated"). That works too, but the else branch keeps both pieces of markup co-located and easier to maintain. We will reuse this pattern in the course project. For now, you have a more expressive way to render either of two templates depending on a single boolean.