Home > Enterprise >  Angular bind formControl based on expression
Angular bind formControl based on expression

Time:05-27

I have 2 arrays in my request data. One contains included products, other - excluded. You can't use both at the same time. So i have such HTML:

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

Here is my 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);
}

Problem: When i slide the toggle the excludeChange gets called, but the input still writed the data into the includedIds, ignoring the slider.

CodePudding user response:

I think you have to subscribe from the exclude$.

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

In component.ts file, you have to define excluded.

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