Home > database >  How to bind ngClass with obserable in angular
How to bind ngClass with obserable in angular

Time:09-06

I have a container something like below

<mat-sidenav-container 
 [ngClass]="{'sidepanel-opened':
 ((isSidePanelVisible$ | async) as isSidePanelVisible) == true }">
</mat-sidenav-container>

Want to use the observable variable in other tags, getting an exception as

Uncaught (in promise): Error: Errors during JIT compilation of template for RiskWorkflowComponent: Parser Error: Missing expected ) at column 53 in [{'sidepanel-opened': ((isSidePanelVisible$ | async) as isSidePanelVisible) == true }] 

CodePudding user response:

Try this

<mat-sidenav-container [ngClass]="{'sidepanel-opened': (isSidePanelVisible$ | async) === true }">
</mat-sidenav-container>

CodePudding user response:

Try this

<input #isSidePanelVisible [checked]="isSidePanelVisible$ | async" hidden />
<mat-sidenav-container [ngClass]="{ red: isSidePanelVisible.checked }"></mat-sidenav-container>

CodePudding user response:

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>
  1. This also allows one to resue the emissions from the observable. Note that each async is an individual subscription.
  2. <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.
  3. 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 we're using *ngIf directive to wrap the emissions in a local variable.
  • Related