Get the following error : Error: Cannot find control with path: 'budgetIncomes -> 0 -> '

Get the following error : Error: Cannot find control with path: 'budgetIncomes -> 0 -> '

尝试将 formarray 与 angular 9 一起使用时出现以下错误:

Error: Cannot find control with path: 'budgetIncomes -> 0 -> '

我尝试了所有方法,但似乎没有任何效果。我不明白为什么找不到路径:

<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),
        })
      ))
    });
  }

}

这里 link 到 stackblitz:https://stackblitz.com/edit/angular-9vk1nr

问题是你使用了[formControlName]="label",也就是属性绑定,意思是它会寻找一个叫做属性 =11=] 在你的组件中 class.

解决方案是使用静态绑定formControlName="label"formControlName="somme"