具有 angular [ngClass] 动态刷新类基于服务中更新的数据

问题描述

我有一个类似这样的模板:

<span [ngStyle]="{'color': s.isDetecting ? 'red' : 'green'}" class="right-icon">
    <i [ngClass]="s.isDetecting ? 'fas fa-eye' : 'fas fa-eye-slash'"></i>
    {{s.detectingStatus}}
</span>

在我的组件中,我基本上是这样的:

// ...
@input() countSensor: PartyInfo = null;

s: DataInfo = null;

ngOnInit(): void {
  this.s = this.countSensor.data;
}

注意:countSensor 从父级传递给子级,并且在服务中每隔几秒更新一次。

现在,使用此代码[ngStyle] 可以正常工作,颜色会在该更改时发生变化,{{s.detectingStatus}} 字符串插值也是如此。 但是,该类似乎没有更新为 [ngClass]:图标始终保持不变。

如何让我的 [ngClass] 刷新类并像 [ngStyle] 一样动态工作?


在 SO 和其他地方研究了一段时间后,我尝试了一些方法

每当我的服务更新我的 detectChanges() 时,使用传递给构造函数ChangeDetectorRef 中的 countSensor 方法手动触发组件更改检测。

但这并没有改变我的行为。

我也尝试在我的模板中使用 async 但我无法做到,因为我的 s.isDetecting 不可观察。 有没有一种简单的方法可以将 observable 绑定到该变量?这可能是一个解决方案...

解决方法

您的值将作为输入出现,因此请在 ngOnchanges 中观看,

ngOnChanges(change:SimpleChange) {
  if(change.countSensor) {
    //put your logic here
  }
}