【发布时间】:2020-07-04 04:20:04
【问题描述】:
我试图弄清楚如何在嵌套的 FormGroup 中访问这个 FormArray,以便默认填充和动态创建表单组。我想创建我的表单,它的值的数据结构将模仿传入的数据。我目前收到以下错误:
错误错误:找不到路径控制:'costs -> 0'
我已尝试“展平”嵌套的 FormGroup,但由于缺少嵌套的“项目”对象,我没有得到正确的输出值。我在下面的 StackBlitz 中评论了该代码。
StackBlitz:https://stackblitz.com/edit/angular-ivy-6lvano
数据
{
"type": "Transportation",
"costs": {
"items": [
{
"category": "Land",
"name": "Taxi",
"amount": 50
},
{
"category": "Land",
"name": "Train",
"amount": 500
},
{
"category": "Air",
"name": "Plane",
"amount": 500
},
]
}
}
组件
export class AppComponent implements OnInit {
invoiceForm: FormGroup;
get costs(): FormArray {
// return this.invoiceForm.get('costs') as FormArray;
return this.invoiceForm.get('costs.items') as FormArray;
}
data = {
"type": "Transportation",
"costs": {
"items": [
{
"category": "Land",
"name": "Taxi",
"amount": 50
},
{
"category": "Land",
"name": "Train",
"amount": 500
},
{
"category": "Air",
"name": "Plane",
"amount": 500
},
]
}
};
constructor(private fb: FormBuilder) {
}
ngOnInit() {
let items = FormArray[10] = [];
if (this.data) {
for (const cost of this.data.costs.items) {
items.push(this.buildExpenseItem(cost.category, cost.name, cost.amount));
}
} else {
items = [ this.buildExpenseItem() ];
}
this.invoiceForm = this.fb.group({
type: [''],
// costs: this.fb.array(items)
costs: this.fb.group({ items: this.fb.array(items) })
});
}
buildExpenseItem(category?: string, name?: string, amount?: number): FormGroup {
return this.fb.group({
category: [category],
name: [name],
amount: [amount]
});
}
addExpenseItem() {
this.costs.push(this.buildExpenseItem());
}
displayOutput() {
console.log(this.invoiceForm.value);
}
}
HTML
<h1>Invoices</h1>
<form [formGroup]="invoiceForm">
<ng-container formArrayName="costs">
<div *ngFor="let cost of costs.controls; let i = index">
<div [formGroupName]="i">
{{ i }}
<input formControlName="category" placeHolder="Category">
<input formControlName="name" placeHolder="Name">
<input formControlName="amount" placeHolder="Amount">
</div>
</div>
</ng-container>
<button (click)="addExpenseItem()">Add</button>
</form>
<button (click)="displayOutput()">Display</button>
【问题讨论】:
标签: angular