如何将ngClass绑定到可观察值

25
在Angular中,是否可以像这样绑定到一个Observable<enum>
<a [ngClass]="{selected: (mapToolBarMode$ | async) === 0 }" />

或者

<a [ngClass]="{selected: (mapToolBarMode$ | async) === MapMode.Pan }" />

其中mapToolBarMode$是可观察对象。

当可观察对象发生变化时,它似乎没有任何作用。

我认为这可能与构造函数中的值不可用有关。如果我这样做,它可以工作,但我不想为MapMode枚举中的每个值都这样做:

private mapModes: typeof MapMode = MapMode;
private isPanSelected = true;
ngOnInit() {
    this.mapToolBarMode.subscribe(v => {
        this.isPanSelected = (v === this.mapModes.Pan);
    })
}

...

[ngClass]="{selected: isPanSelected }"

更新 原来这是由于遗留代码调用了Angular组件。这些调用需要在ngZone的上下文中运行,否则就没有循环。


当然,那应该可以工作吧?MapMode.Pan是什么? - Günter Zöchbauer
如果这不起作用,也许尝试将其更改为 Oberservable<boolean> 并在组件代码中使用 .map() 进行 === - Fredrik Lundin
1
如果你能够执行 this.mapToolBarMode.subscribe,那么你的绑定应该是 <a [ngClass]="{selected: (mapToolBarMode | async) === 0 }" />(没有 $)。 - Günter Zöchbauer
“值在构造函数中不可用”。来自异步请求的值在构造函数中肯定还不可用,这是异步的本质。 - Günter Zöchbauer
1个回答

23

也许你在问题中漏掉了一些细节,在我的例子中它正常工作:

或者你的可观察对象已经completed了?可能是HTTP请求吗?

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 (click)="toggle()"
          [ngClass]="{selected: (mapToolBarMode$ | async) === 0 }"
          >
          Hello {{name}}, click to toggle color
      </h2>
    </div>
  `,
  styles: [
    '.selected { color: red; }'
  ]
})
export class App {
  name:string;

  mapToolBarMode$ = new Subject();

  constructor() {
    this.name = 'Angular2'
  }

  private _curState = 1;
  toggle() {
    if (++this._curState > 1) this._curState = 0;

    this.mapToolBarMode$.next(this._curState);
  }
}

演示链接:https://plnkr.co/edit/h0YIPpCh9baJgxCsBQrY?p=preview


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接