angularangular-ng-if

Angular *ngIf variable with async pipe multiple conditions


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.


Solution

  • You can do this:

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

    Keep in mind that when using a subscription from a http-request, this would trigger the request twice. So you should use some state-management pattern or library, to not make that happen.

    Here is a stackblitz.