有没有更好的方法将值推送到表单控件,其中数组作为 Angular 中的值

Is there a better way to push a value to a form control with an array as a value in Angular

我目前有一个多 select 列表,我想从组件中添加一个值。我现在这样做的方式不会在 UI 上更新,也不会 运行 我的自定义验证器。如果我控制表单控件的值,它会显示正确的值。有没有更好的方法来做到这一点,或者谁能解释为什么会这样?

<mat-form-field appearance="fill">
  <mat-label>Toppings</mat-label>
  <mat-select [formControl]="toppings" multiple>
    <mat-option *ngFor="let topping of toppingList" [value]="topping">
      {{topping}}
    </mat-option>
  </mat-select>
</mat-form-field>
<br />
<button (click)="add()">Add Onion To List</button>
export class SelectMultipleExample {
      toppings = new FormControl([]);
      toppingList: string[] = [
        'Extra cheese',
        'Mushroom',
        'Onion',
        'Pepperoni',
        'Sausage',
        'Tomato',
      ];
    
      ngOnInit() {
        this.toppings.addValidators(this.validator);
      }
    
      add() {
        this.toppings.value.push('Onion');
        console.log(this.toppings.value);
      }
    
      validator(control: AbstractControl): ValidationErrors | null {
        console.log('Checked');
        return null;
      }

https://stackblitz.com/edit/angular-dwztco?file=src/app/select-multiple-example.ts

您需要致电 FormControl.setValue 才能更新。 FormControl.value 应该是只读的。

改变

this.toppings.value.push('Onion');

this.toppings.setValue([...this.toppings.value,"Onion"]);

请注意,当多次单击该按钮时,这会将重复值“Onion”添加到列表中,但是当您手动 select 列表中的某些内容时,重复值会自动删除。无论如何,这超出了这个问题的范围。