Lewis Morgans
Lewis Morgans

Reputation: 261

Dynamically adding form fields to reactive forms in Angular 8

I'm having some trouble getting form fields to populate from an array. My original thinking is to input the array from individual components to a single component that will handle the form. Instead of making multiple forms. But I can't seem to get it to work. Any help would be appreciated! I've been through Google/stack/medium and can't seem to find anything. I've done an example on plunkr.

https://stackblitz.com/edit/angular-t7hcq6

In the ts file:

  public demoForm: FormGroup;
  public arrayItems: data = [];

  private formFields = ["Sku", "Title"];

  constructor(private _formBuilder: FormBuilder) {
    this.demoForm = this._formBuilder.group({
      demoArray: this._formBuilder.array([])
    });
  }

  ngOnInit() {
    this.formFields.map(field => {
      this.arrayItems.push({ title: field });
      this.demoArray.push(this._formBuilder.control(''));
    });
  }

  get demoArray() {
    return this.demoForm.get("demoArray") as FormArray;
  }

In the template:

<form [formGroup]="demoForm">
   <div formArrayName="demoArray" 
      *ngFor="let arrayItem of arrayItems; let i=index">
      <input type="checkbox"[formControl]="demoArray[i]">
      <label>{{arrayItem.title}}</label>
   </div>
</form>

Thank you guys.

Upvotes: 3

Views: 10112

Answers (1)

Henrique Erzinger
Henrique Erzinger

Reputation: 1147

change your template like so:

<form [formGroup]="demoForm">
   <div formArrayName="demoArray" 
      *ngFor="let arrayItem of arrayItems; let i=index">
      <input type="checkbox" [formControlName]="i"> <!-- this line -->
      <label>{{arrayItem.title}}</label>
   </div>
</form>

Upvotes: 3

Related Questions