BehaviorSubject的角度绑定复选框

问题描述 投票:0回答:1

在Angular中,如何将复选框绑定到rxjs BehaviorSubject?我想更改复选框以触发执行一些操作的订阅。目前,我有以下黑客入侵:

openSessionsOnly$ = new BehaviorSubject(false);

这在我的模板中:

<input type="checkbox" #openSessionsOnly [checked]="openSessionsOnly$.value" (change)="openSessionsOnly$.next(openSessionsOnly.checked)"/>

虽然有效,但我感觉自己做错了。我尝试使用[(ngModel)],但它似乎不适用于可观察对象。我是否需要像已经使用的那样使用单独的属性和事件绑定?

angular rxjs
1个回答
0
投票

使用TypeScript属性很容易完成:

private openSessionsOnly$ = new BehaviorSubject(false);

get openSessionsOnly(): boolean {
  return this.openSessionsOnly$.value;
}
set openSessionsOnly(v: boolean) {
  this.openSessionsOnly$.next(v);
}

现在可以在模板中绑定事件或直接使用ngModel

<!-- you will need a name if inside a form -->
<input type="checkbox" [(ngModel)]="openSessionsOnly" />

[请注意,您不能保证下一次将被称为最小次数,因此您可能想在可观察的管道中抛出distinctUntilChanged

© www.soinside.com 2019 - 2024. All rights reserved.