New in Angular 4: NgIf with else

- Tom Trapp

The old way

<p *ngIf="isAuthenticated">
Logged in as
</p>
<p *ngIf="!isAuthenticated">
Please login: <button>Login</button>
</p>

The new way with else

<p *ngIf="isAuthenticated; else userNotLoggedIn">
Logged in as
</p>
<ng-template #userNotLoggedIn>
<p>
Please login: <button>Login</button>
</p>
</ng-template>

THE NEW WAY COMBINING IF AND ELSE

<div *ngIf="isAuthenticated; then showUser else userNotLoggedIn"></div>
<ng-template #showUser>
<p>
Logged in as
</p>
</ng-template>
<ng-template #userNotLoggedIn>
<p>
Please login: <button>Login</button>
</p>
</ng-template>

Now you can have just one if-condtion where you can specify “then” or “else”.