I am using Angular's Reactive forms and one of the Form Controls is a select input. The options change dynamically and when the user has selected a value and then the options change, the old value is still the value of the Form Control, even when it's not longer in the options' list (and therefore not an acceptable value).
HTML:
<mat-select formControlName="example">
<mat-option *ngFor="let example of examples_filtered" [value]="example">
{{ example.frontend_name }}
</mat-option>
</mat-select>
TypeScript:
this.myForm.controls['someControl'].valueChanges.subscribe(
(value) => {
this.examples_filtered = [];
this.examples.forEach((example: Example, index: Number, array: Example[]) => {
if (example.value_id === value.id) {
this.examples_filtered.push(example);
}
});
}
);
Since this Form Control uses Validators.required, the expected behavior is that the Form Control gets emptied (i.e. the value gets set to null) and its status is changed to 'INVALID'.
The actual result is that the old value from the previously filtered examples is still selected in the Form Control and the Validators.required marks the Form Control as valid.
Should I do this manually (i.e. custom code) or is there a mechanism that Angular supports that solves this?
this.myForm.controls['example'].valueChangesinstead ofthis.myForm.controls['someControl'].valueChanges? - Just Shadowthis.myForm.controls['example'].setValue(null)(nothing selected) orthis.myForm.controls['example'].setValue(this.examples_filtered[0])(first element selected) at the end of your subscribe function. - Federico Galfionethis.myForm.controls['example'].reset()and now I get the expected behavior. Thank you! - Nikolay Nikolov