New in Angular 4 - NgIf with else

13.05.2017Tom Trapp
Mobile Angular Hands-on

The traditional approach

1
2
3
4
5
6
<p *ngIf="isAuthenticated">
    Logged in as
</p>
<p *ngIf="!isAuthenticated">
    Please login: <button>Login</button>
</p>

The new approach with else

1
2
3
4
5
6
7
8
<p *ngIf="isAuthenticated; else userNotLoggedIn">
    Logged in as
</p>
<ng-template #userNotLoggedIn>
    <p>
        Please login: <button>Login</button>
    </p>
</ng-template>

The new approach combined with if and else

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<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 only have one logical if-condition with both then or else cases.


This text was automatically translated with our golang markdown translator.

Tom Trapp

Tom Trapp – Problemlöser, Innovator, Sportler. Am liebsten feilt Tom den ganzen Tag an der moderner Software und legt viel Wert auf objektiv sauberen, leanen Code.