簡體   English   中英

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

[英]How to use mat-select with reactive forms formarray angular

到目前為止,我已經編寫了以下代碼

<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

問題:正如您在堆棧閃電中看到的那樣,它沒有顯示初始值,並且如果我們選擇該選項,那么它也將不起作用,並且如果我們選擇任何選項,那么這些選項也會從選擇中消失。

您的示例看起來很奇怪:

{
  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數組。

分叉的Stackblitz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM