如何在angular中将ngClass与observable绑定



我有一个类似下面的容器

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

想要在其他标签中使用可观察变量,将异常作为

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 }] 

我通常觉得用*ngIf包装<ng-container>标记中的async变量更方便,这样它们就可以重用了。

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

如果只想动态调整一个类,也可以使用[class.sidepanel-opened]变体。

<ng-container 
*ngIf="{ value: (isSidePanelVisible$ | async) } as isSidePanelVisible"
>
<mat-sidenav-container [class.sidepanel-opened]="isSidePanelVisible.value">
</mat-sidenav-container>
</ng-container>
  1. 这也允许从可观测到的数据中恢复排放。请注意,每个async都是一个单独的订阅
  2. <ng-container>是特定于Angular的标签,在最终生成的DOM中被注释掉,因此不会在DOM中产生额外的元素
  3. 如果async没有封装在对象中,即直接使用*ngIf="(isSidePanelVisible$ | async) as isSidePanelVisible",则当可观察对象发出false时,<ng-container>将不会呈现,因为*ngIf指令将解析为*ngIf=false

试试这个

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

试试这个

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

最新更新