Angular *ngIf variable with async pipe multiple conditions

Vitaly picture Vitaly · Mar 15, 2018 · Viewed 31.4k times · Source

There's quite good doc of using *ngIf in Angular: https://angular.io/api/common/NgIf But, is that possible to have *ngIf async variable and multiple checks on that? Something like:

<div *ngIf="users$ | async as users && users.length > 1">
...
</div>

Of course, it's possible to use nested *ngIf, like:

<div *ngIf="users$ | async as users">
    <ng-container *ngIf="users.length > 1">
    ...
    </ng-container>
</div>

but it'd be really nice to use only one container, not two.

Answer

alsami picture alsami · Mar 15, 2018

Simply do it like this

<div *ngfor="let user of users$ | async" *ngIf="(users$ | async)?.length > 1">...</div>

For "more complex" scenario do the following

<div  *ngfor="let user of users$ | async" *ngIf="(users$ | async)?.length > 1 && (users$ | async)?.length < 5">...</div>

Edit: Previous wouldn't work since you cannot use *ngFor and *ngIf without using ng-template. You would do it like that for instance

<ng-template ngFor let-user [ngForOf]="users$ | async" *ngIf="(users$ | async)?.length > 1 && (users$ | async)?.length < 5">
  <div>{{ user | json }}</div>
</ng-template>

Here is a stackblitz.