Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 711
Vitaly Avatar asked Mar 15 '18 10:03

Vitaly


2 Answers

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.

like image 181
alsami Avatar answered Sep 17 '22 12:09

alsami


I hit the same issue of needing an *ngIf + async variable with multiple checks.

This ended up working well for me.

<div *ngIf="(users$ | async)?.length > 0 && (users$ | async) as users"> ... </div> 

or if you prefer

<div *ngIf="(users$ | async)?.length > 0 && (users$ | async); let users"> ... </div> 

Explanation

Since the result of the if expression is assigned to the local variable you specify, simply ending your check with ... && (users$ | async) as users allows you to specify multiple conditions and specify what value you want the local variable to hold when all your conditions succeed.

Note

I was initially worried that using multiple async pipes in the same expression may create multiple subscriptions, but after some light testing (I could be wrong) it seems like only one subscription is actually made.

like image 25
Keego Avatar answered Sep 19 '22 12:09

Keego