我正在尝试将mat-select与表单数组一起使用。由于某种原因,它给了我以下错误: 对于数组中的每个项目,都没有用于路径为'profileGroup-> meterings-> 0-> selected'的表单控制的值访问器。
<div formGroupName="profileGroup" [class.active]="!show" class="inner-area">
<mat-form-field formArrayName="meterings">
<mat-select multiple>
<div *ngFor="let metering of meteringArray; let i = index">
<div [formGroupName]="i">
<mat-option formControlName="selected" [value]="metering.value">
{{ metering.value.name }}
</mat-option>
</div>
</div>
</mat-select>
</mat-form-field>
<div>
this.mainForm = this.fb.group({
profileGroup: this.fb.group({
meterings: this.fb.array([]),
from: [""],
to: [""]
})
});
addMetering(metering: Metering) {
const control = (this.mainForm.controls["profileGroup"] as FormGroup).get("meterings") as FormArray;
control.push(this.createItem(metering));
}
createItem(metering: Metering): FormGroup {
return this.fb.group({
name: metering.name,
id: metering.meteringId,
selected: false
});
}
get meteringArray() {
return ((this.parent.controls["profileGroup"] as FormGroup).get("meterings") as FormArray).controls;
}
答案 0 :(得分:0)
您混入了不同的概念。选择多个材质是存储数组(以及对象数组或字符串数组)的控件。然后,您遍历元素的简单数组以在这些元素中进行选择。没有意义的使用FormArray,也没有向Array添加元素。所以我想你有一些像
meterings=[
{name:"metering 1",id:1}
{name:"metering 2",id:2}
{name:"metering 3",id:2}
]
this.mainForm = this.fb.group({
profileGroup: this.fb.group({
meterings: [[]],
from: [""],
to: [""]
})
});
.html
<div formGroupName="profileGroup" [class.active]="!show" class="inner-area">
<mat-form-field >
<mat-select fromGroupName="meterings">
<mat-option *ngFor="let metering of meterings; let i = index"
[value]="metering.value">
{{ metering.value.name }}
</mat-option>
</mat-select>
</mat-form-field>
<div>
您的表单可以获取值,例如
mainform={
profileGroup:{
metering:[1,2]
from:''
to:''
}
}
另一件事是,您要输入一个FormControls的FormArray。但是,那么您就不必使用选择倍数了
this.mainForm = this.fb.group({
profileGroup: this.fb.group({
meterings: this.fb.array([]),
from: [""],
to: [""]
})
});
.html
<div formGroupName="profileGroup" [class.active]="!show" class="inner-area">
<mat-form-field formArrayName="meterings">
<div *ngFor="let metering of meteringArray; let i = index" [formGroupName]="i">
<mat-checkbox formControlName="selected">
</mat-checkbox>
<input mat-input formControlName="name">
<input mat-input formControlName="id">
</div>
</mat-form-field>
</div>
您的来信就像
mainform={
profileGroup:{
metering:[
{id:1,name:"metering 1",true},
{id:1,name:"metering 1",false}
]
from:''
to:''
}
}