如何将ngclass绑定到可观察的值

jen*_*ent 11 observable rxjs angular

Observable<enum>在Angular中绑定到这样的可能吗?

<a [ngClass]="{selected: (mapToolBarMode$ | async) === 0 }" />
Run Code Online (Sandbox Code Playgroud)

要么

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

哪里mapToolBarMode$是可观察的

它似乎没有像可观察到的变异那样做任何事情.

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

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

...

[ngClass]="{selected: isPanSelected }"
Run Code Online (Sandbox Code Playgroud)

更新 原来,这是遗留代码调用角度分量做.那些调用需要在ngZone的上下文中运行,否则就没有循环

mxi*_*xii 6

也许你错过了问题中的一个细节,在我的例子中它的工作正常:

或者您的观察结果已经存在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);
  }
}
Run Code Online (Sandbox Code Playgroud)

现场演示:https://plnkr.co/edit/h0YIPpCh9baJgxCsBQrY?p = preview