1

The example in Angular official docs show the following code:

@Component({
  template: `
    <form [formGroup]="form">
      <div formArrayName="cities">
        <div *ngFor="let city of cities.controls; index as i">
          <input [formControlName]="i">
        </div>
      </div>
    </form>
  `,
})
export class NestedFormArray {
  form = new FormGroup({
    cities: new FormArray([
      new FormControl('SF'),
      new FormControl('NY'),
    ]),
  });

  get cities(): FormArray { return this.form.get('cities') as FormArray; }

}

I can't understand why we need the formArrayName directive when the code works even without it?

<form [formGroup]="form">
        <div *ngFor="let city of cities.controls; index as i">
          <input [formControlName]="i">
        </div>
 </form>

1 Answer 1

2
<form [formGroup]="form">
        <div *ngFor="let city of cities.controls; index as i">
          <input [formControlName]="i">
        </div>
 </form>

It's not working without FormArrayName for structure like:

new FormGroup({
  cities: new FormArray([
    new FormControl('SF'),
    new FormControl('NY'),
  ]),
});

<input [formControlName]="i"> - says how to syncs a FormControl(input) to an existing <form [formGroup]="form">.

So it properly work for that structure:

new FormArray([
    new FormControl('SF'),
    new FormControl('NY'),
]);
Sign up to request clarification or add additional context in comments.

3 Comments

I'm sorry, can't understand what you mean.
TLDR without FormArrayName it will work for form = FormArray([new FormControl('SF'), new FormControl('NY')])
Maybe i misunderstand you, check this example pls

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.