Conditional (if, else) in Angular 2 Conditional (if, else) in Angular 2 express express

Conditional (if, else) in Angular 2


If you need the "else", perhaps the best way is to use NgSwitch (https://angular.io/docs/ts/latest/api/common/index/NgSwitch-directive.html)

So something like:

<div [ngSwitch]="User?.Identity?.IsAuthenticated">  <b *ngSwitchCase="true">Sign Out</b>  <b *ngSwitchDefault>Sign In</b></div>


With Angular 4, this is now possible:

  • SYNCHRONOUSLY

    lets assume that we've defined this class variable:

    shown: boolean = true;

    If else syntax:

    <button (click)="shown = !shown">toggle 'shown' variable</button><div *ngIf="shown; else elseBlock">If shown</div><ng-template #elseBlock>else not shown</ng-template>

    Note that ng-template must be used in order for this structural directive to work, so if you have a custom component, wrap it inside ng-template. Below is an alternative syntax which also binds to the same class variable.

    If then else syntax:

    <button (click)="shown = !shown">toggle 'shown' variable</button><div *ngIf="shown; then primaryBlock; else secondaryBlock"></div><ng-template #primaryBlock>If shown</ng-template><ng-template #secondaryBlock>else not shown</ng-template>

  • ASYNCHRONOUSLY

    class:

    userObservable = new Subject<{first: string, last: string}>();onButtonClick() {  this.userObservable.next({first: 'John', last: 'Smith'});}

    template:

    <button (click)="onButtonClick()">Display User</button><div *ngIf="userObservable | async as user; else loading">  Hello {{user.last}}, {{user.first}}!</div><ng-template #loading>Waiting for click...</ng-template>