I usually find it neater to wrap async
variables in <ng-container>
tags with *ngIf
so that they can be reused.
<ng-container
*ngIf="{ value: (isSidePanelVisible$ | async) } as isSidePanelVisible"
>
<mat-sidenav-container
[ngClass]="{'sidepanel-opened': isSidePanelVisible.value}"
>
</mat-sidenav-container>
</ng-container>
If you'd want to dynamically adjust only one class, you could also use the [class.sidepanel-opened]
variant.
<ng-container
*ngIf="{ value: (isSidePanelVisible$ | async) } as isSidePanelVisible"
>
<mat-sidenav-container [class.sidepanel-opened]="isSidePanelVisible.value">
</mat-sidenav-container>
</ng-container>
- This also allows one to resue the emissions from the observable. Note that each
async
is an individual subscription.
<ng-container>
are Angular specific tags that are commented out in the final generated DOM, and so don't lead to additional elements in DOM.
- If the
async
isn't wrapped in an object, i.e. if it's used directly, *ngIf="(isSidePanelVisible$ | async) as isSidePanelVisible"
, the <ng-container>
won't be rendered when the observable emits false
since *ngIf
directive would resolve to *ngIf=false
.