New Features for ngIf Starting with Angular 4

Angular 4 is due to arrive in just a few days, and with it comes great additions to the built-in ngIf template directive. Namely, we can now define a template to use for an else clause, and we can assign a local variable that holds the resulting value of the if clause.

Here’s how to use these two new features for ngIf:

Else Clause

So it used to be, in order to have an else clause as part of an ngIf statement, you would have to instead create another ngIf statement with the negation of the first statement:

<div *ngIf="likeThis">
  Like this!
</div>
<div *ngIf="!likeThis">
  Like that!
</div>

But now we can define an else clause with the reference name for a template that we define with ng-template:

<div *ngIf="things.car; else noCar">
  Nice car!
</div>
<ng-template #noCar>
  Call a Uber.
</ng-template>

Local Variable Assignment

Often the resulting value of an if statement won’t just be the boolean true or false but will instead be a value that you may want to reference easily. With the new ngIf you can easily assign the result of the if statement to a local variable. For example, our things object looks like this in our component class:

things = {
  car: 'Honda',
  shoes: 'Nike',
  shirt: 'Tom Ford',
  watch: 'Timex'
};

And you can reference the result of the if statement like this:

<div *ngIf="things.car; let car">
  Nice {{ car }}!
</div>
<!-- Nice Honda! -->

You can of course combine both an else clause and a local variable assignment:

<div *ngIf="things.car; else noCar; let car">
  Nice {{ car }}!
</div>
<ng-template #noCar>
  Call a Uber.
</ng-template>

ngIf with Async Pipe

The new functionalities for the ngIf directive become very powerful when used in combination with the async pipe, as explained in this post from Angular University.

You can, for example, use the async pipe to automatically subscribe to an observable, define a loading template with the else clause and place the resulting value from the observable into a local variable.

Let’s create a simple observable to illustrate:

// ...
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/delay';

// ...
export class AppComponent {
  things$ = Observable.of({
    car: 'Honda',
    shoes: 'Nike',
    shirt: 'Tom Ford',
    watch: 'Timex'
  }).delay(1000);
}

Our observable mimics a network call by waiting for 1 second before emitting the data.

Now you can use the async pipe to subscribe to the things$ observable, define an else clause with a template for a loading message, and declare a local variable that you’ll be able to access once the observable gets its data:

<div *ngIf="things$ | async; else loading; let things">
  Nice {{ things.watch }}! <!-- Nice Timex! -->
</div>
<ng-template #loading>
  Loading your things...
</ng-template>
✖ Clear

🕵 Search Results

🔎 Searching...