In my experience, I prefer wrapping async
variables in <ng-container>
tags with *ngIf
for a cleaner structure that allows for reusability.
<ng-container
*ngIf="{ value: (isSidePanelVisible$ | async) } as isSidePanelVisible"
>
<mat-sidenav-container
[ngClass]="{'sidepanel-opened': isSidePanelVisible.value}"
>
</mat-sidenav-container>
</ng-container>
If you only need to dynamically adjust one class, the [class.sidepanel-opened]
variant can also be helpful.
<ng-container
*ngIf="{ value: (isSidePanelVisible$ | async) } as isSidePanelVisible"
>
<mat-sidenav-container [class.sidepanel-opened]="isSidePanelVisible.value">
</mat-sidenav-container>
</ng-container>
- This method enables the reuse of emissions from the observable, keeping in mind that each
async
operation creates an individual subscription.
<ng-container>
are Angular-specific tags that are excluded from the final DOM, ensuring they do not result in additional elements added to the document.
- If the
async
variable is not wrapped in an object and used directly like *ngIf="(isSidePanelVisible$ | async) as isSidePanelVisible"
, the <ng-container>
will not render when the observable emits false
due to the resolution of the *ngIf
directive as false
.