Search code examples
angulartypescriptcontrolsangular-reactive-forms

Cannot find control with path error while Initializing Form Array With existing array of multiple objects in angular 13


Hi am new to Angular am looking to initialize form array with existing array consists of multiple objects in angular. am getting following error

Cannot find control with path: 'variable-> 0 -> id'

HERE IS MY HTML:

<form [formGroup]="myForm">
  <div formArrayName="box">
    <div *ngFor="let b of getForm(); let i = index">
      <fieldset [formGroupName]="i">
        <legend> <h3>FRUIT DETAILS {{ i + 1 }}:</h3>  </legend>
        <label>Fruit Name: </label>
        <input [formControlName]="name" />
        <label>Fruit Value: </label>
        <input [formControlName]="value" />
      </fieldset>
    </div>
  </div>
  <br />
</form>

<pre>{{ myForm.value | json }}</pre>

AND HERE'S MY TS:

myForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.myForm = this.fb.group({
      box: this.fb.array([]),
    });

    let fruits = {
      data: [{name: 'Apple', value: 10}, {name: 'Orange', value: 5},{name: 'Banana', value: 20}]
    };

    for (let f of fruits.data) {
      const control = <FormArray>this.myForm.get('box');
    control.push(this.fb.group({name: f.name, value: f.value}));

    console.log(f);

    }

    this.myForm.patchValue({ box: fruits.data });
    //console.log(this.myForm.value);
  }

  getForm(): any {
    return this.myForm.get('box')['controls'];
  }

Solution

  • I changed two things to make it work:

    In the TS File I refactored the getForm() method because in my fresh Angular 15 project your code didn't seem to be executable anymore. Therefore you might prevent potential future problems by adapting it as follows:

    getForm(): any {
        const form = this.myForm.get('box') as FormArray;
        return form['controls'];
    }
    

    In the HTML File I removed the brackets around formControlName, since otherwise name and value would be interpreted as a variable and not as string:

    <form [formGroup]="myForm">
        <div formArrayName="box">
          <div *ngFor="let b of getForm(); let i = index">
            <fieldset [formGroupName]="i">
              <legend> <h3>FRUIT DETAILS {{ i + 1 }}:</h3>  </legend>
              <label>Fruit Name: </label>
              <input formControlName="name" />
              <label>Fruit Value: </label>
              <input formControlName="value" />
            </fieldset>
          </div>
        </div>
       <br />
    </form>