angular - SELECT的表单控件不会在选项列表更改时更新值

标签 angular html-select angular-reactive-forms

我正在使用 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/

相关文章:

angular - 它相当于 Blazor 中的 Angular/Vue 事件发射吗?

node.js - 无法正式安装 "Cannot read property ' 种'未定义'

javascript - 连接输出参数值和绑定(bind)表达式

javascript - 在选择列表中选择默认选定项的最佳方式是什么? (落下)

angular - 如何确保在以 Angular 渲染 react 形式之前加载可观察数据

javascript - 在 Angular 2 中处理 CometD channel 不起作用

css - 如何从 select 标签更改选项的背景颜色?

css - 使用 ajax 或 jquery 更改下拉宽度

angular - 响应式(Reactive)表单 valueChanges observable 重置表单值

Angular 2 Reactive Forms 找不到控件