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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With