Search code examples
angularangular-ng-if

Angular 5 ngIfElse: Storing conditional result in a variable


Code:

<mat-icon [ngClass]='{ rotate: !users }'>refresh</mat-icon>
<div *ngIf="usersObservable | async as users; else loading">
  ...
</div>
<ng-template #loading let-users>
  Waiting...
</ng-template>

Expected: rotate class applied to <mat-icon> while users are loading

Result: class not applied

Question: Is it possible to store/use boolean result of ngIfElse evaluation?

P.S.: In this example, I want rotate class to be applied to <mat-icon> until HTTP request completed.


Solution

  • The as users variable is only in scope for bindings on or inside the tag where the *ngIf is applied.

    You'd do something like

    <mat-icon [ngClass]='{ rotate: !(usersObservable | async)?.users }'>refresh</mat-icon>
    

    Ensure your observable behaves properly when subscribed to more than once. For example some of the methods mentioned in What is the correct way to share the result of an Angular Http network call in RxJs 5?