选项列表更改时,用于select的Form Control不会更新值

时间:2019-04-15 08:28:43

标签: angular html-select angular-reactive-forms

我正在使用Angular的Reactive表单,并且Form控件之一是select输入。选项会动态更改,并且当用户选择一个值然后选项更改时,即使值不再出现在选项列表中(因此也不是可接受的值),旧值仍是Form Control的值。 / p>

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),并且其状态更改为“无效”。

实际结果是,仍在表单控件和验证器中选择了先前过滤的示例中的旧值。必需将表单控件标记为有效。

我应该手动执行此操作(即自定义代码)还是Angular支持的机制来解决此问题?

1 个答案:

答案 0 :(得分:1)

以下将根据需要工作。关键是使用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()选择更改:EventEmitter

     

用户更改所选值时发出的事件。

相关问题