到目前为止,我已经编写了以下代码
<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 .
问题:正如您在 stackblitz 中看到的,它没有显示初始值,如果我们选择该选项,那么它也不起作用,并且如果我们选择该选项,选项也会从选择中消失选择任意选项。
最佳答案
你的例子看起来很奇怪:
{
initial: 'one', <------------ it is not in options array
options: ['two', 'three', 'four']
}
但是无论如何,如果您想让它与 FormArray 一起使用,那么您应该映射初始
值而不是整个对象:
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
数组。
关于javascript - 如何使用 mat-select 与 react 形式 formarray Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57646437/