如何在反应形式formarray angular中使用mat-select

时间:2019-08-25 13:29:00

标签: javascript angular typescript angular-reactive-forms

到目前为止,我已经编写了以下代码

<form [formGroup]="testForm">
    <div formArrayName="selects">
        <mat-form-field *ngFor="let select of selects.controls; let i = index">
            <mat-select [formControlName]="i">
                <mat-option *ngFor="let option of select.value.options" [value]="option">{{ option }}</mat-option>
            </mat-select>
        </mat-form-field>
    </div>
</form>

在组件文件中

testForm: FormGroup;

get selects() {
  return this.testForm.get('selects') as FormArray;
}

data = [{
  initial: 'one',
  options: ['two', 'three', 'four']
}, {
  initial: 'a',
  options: ['b', 'c', 'd']
}];

constructor(private formBuilder: FormBuilder) { }

ngOnInit() {
  this.testForm = this.formBuilder.group({
    selects: this.formBuilder.array([]),
  });

  for (let i = 0; i < this.data.length; i++) {
    this.selects.push(new FormControl(this.data[i]));
  }
}

但是到目前为止,这还行不通。我在这里做错了什么?

找到Stackblitz here

问题:如您在堆栈闪电中看到的那样,它没有显示初始值,如果我们选择了该选项,那么它也将不起作用,并且如果我们选择了这些选项,这些选项也会从选择中消失选择任何选项。

1 个答案:

答案 0 :(得分:2)

您的示例看起来很奇怪:

{
  initial: 'one', <------------  it is not in options array
  options: ['two', 'three', 'four']
}

但是无论如何,如果要使其与FormArray一起使用,则应该映射initial值而不是整个对象:

this.testForm = this.formBuilder.group({
  selects: this.formBuilder.array(this.data.map(item => new FormControl(item.initial))),
});

您的html应该如下所示:

<mat-form-field *ngFor="let select of data; let i = index">
    <mat-select [formControlName]="i">
        <mat-option *ngFor="let option of select.options" [value]="option">{{ option }}</mat-option>
    </mat-select>
</mat-form-field>

如您所见,我遍历了原始data数组。

Forked Stackblitz