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

<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

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

最佳答案

您的示例看起来很奇怪:

{
  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

关于javascript - 如何在 react 形式formarray angular中使用mat-select,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57646437/

10-12 03:49