当尝试使用带有角度9的formarray时出现以下错误:
错误:找不到路径为'budgetIncomes-> 0->'
的控件
我尝试了evrything,但似乎没有任何效果。我不明白为什么找不到路径:
<form *ngIf="incomeForm" [formGroup]="incomeForm">
<div formArrayName="budgetIncomes">
<h3>Income</h3>
<div *ngFor="let item of incomesArray.controls; let i=index"[formGroupName]="i">
<input type="text" [formControlName]="label">
<input type="number" [formControlName]="somme">
</div>
<button (click)="addIncome()">Add Income</button>
</div>
</form>
<p class="result" [ngStyle]="{'color': getSum()>=0? 'green' : 'red'}">{{getSum()}}</p>
和.ts:
import { Component, OnInit, SimpleChanges } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { FormArray } from '@angular/forms';
import { Budget } from '../budget';
export interface BudgetIncomes {
label: string;
somme: number;
}
const ELEMENT_DATA: BudgetIncomes[] = [
{label: 'Hydrogen', somme: 10},
];
@Component({
selector: 'app-income',
templateUrl: './income.component.html',
styleUrls: ['./income.component.scss']
})
export class IncomeComponent implements OnInit {
incomeForm: FormGroup;
sum;
getSum() {
// 1st way
return this.incomesArray.value.reduce((prev, next) => prev + +next, 0);
}
createBudget(): FormGroup {
return this.fb.group(ELEMENT_DATA.map(x => new FormGroup({
label : new FormControl(x.label),
somme : new FormControl(x.somme),
})
));
}
get incomesArray(): FormArray {
return this.incomeForm.get('budgetIncomes') as FormArray;
}
addIncome() {
this.incomesArray.push(this.fb.group(this.createBudget()));
}
constructor(private fb: FormBuilder) {
}
ngOnInit(): void {
this.incomeForm = this.fb.group({
budgetIncomes: this.fb.array(ELEMENT_DATA.map(x => new FormGroup({
label : new FormControl(x.label),
somme : new FormControl(x.somme),
})
))
});
}
}
这里是stackblitz的链接:https://stackblitz.com/edit/angular-9vk1nr
答案 0 :(得分:0)
问题是您使用[formControlName]="label"
,这是属性绑定,这意味着它将在组件类中查找名为label
的属性。
解决方案是使用静态绑定:formControlName="label"
和formControlName="somme"
。