我正在使用 Angular 的 Reactive 表单,其中一个表单控件是选择输入。选项动态更改,当用户选择一个值然后选项更改时,旧值仍然是表单控件的值,即使它不再在选项列表中(因此不是可接受的值)。
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);
}
});
}
);
由于此表单控件使用 Validators.required,预期行为是表单控件被清空(即值被设置为 null)并且其状态更改为“无效”。
实际结果是表单控件中仍然选择了先前过滤示例中的旧值,并且 Validators.required 将表单控件标记为有效。
我应该手动执行此操作(即自定义代码)还是 Angular 支持解决此问题的机制?
最佳答案
以下将按需要工作。关键是使用Angular的selectionChange
事件将按预期直接更新您的表单控件(在输入附加的事件处理程序之前)。
模板
<mat-select formControlName="example" (selectionChange)="this.exampleSelectionChangedHandler($event)">
<mat-option *ngFor="let example of examples_filtered" [value]="example">
{{ example.frontend_name }}
</mat-option>
</mat-select>
组件
public exampleSelectionChangedHandler(e: MouseEvent){
this.examples_filtered = [];
this.examples.forEach((example: Example, index: Number, array: Example[]) => {
if (example.value_id === value.id) {
this.examples_filtered.push(example);
}
}
奇怪的是 selectionChange 选项不是“智能感知”,但绝对是一个 mat-select 指令,因为我们可以阅读 here :
@Output() selectionChange: EventEmitter
Event emitted when the selected value has been changed by the user.
关于angular - SELECT的表单控件不会在选项列表更改时更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55685204/