Angular 根据表达式绑定 formControl

Angular bind formControl based on expression

我的请求数据中有 2 个数组。一个包含包含的产品,其他 - 排除在外。您不能同时使用两者。所以我有这样的 HTML:

<input [formControl]="this.exclude$ ? excludedFormControl : includedFormControl>
<mat-slide-toggle (change)="excludeChange($event.checked)"></mat-slide-toggle>

这是我的TS:

exclude$ = new BehaviorSubject<boolean>(false);

currentFilter = {
    productsSection: {
        includedIds: [],
        excludedIds: [],
    },
};

includedFormControl: FormControl = new FormControl(
    this.currentFilter.productsSection.includedIds ? this.currentFilter.productsSection.includedIds : [],
);

excludedFormControl : FormControl = new FormControl(
    this.currentFilter.productsSection.excludedIds? this.currentFilter.productsSection.excludedIds: [],
);

excludeChange(value: boolean): void {
    this.filterForm.patchValue({
        includedIds: [],
        excludedIds: [],
     });
     this.exclude$.next(value);
}

showFormValue() {
    console.log(this.filterForm.value);
}

问题: 当我滑动开关时调用了 excludeChange,但输入仍然将数据写入 includedIds,忽略了滑块。

我认为你必须从 exclude$ 订阅。

<input [formControl]="excluded ? excludedFormControl : includedFormControl">

在component.ts文件中,你必须定义excluded.

excluded = false;
this.exclude$.subscribe(res => {
  this.excluded = res;
});