Home > Blockchain >  How to use 1 formControlName for dynamic fields?
How to use 1 formControlName for dynamic fields?

Time:07-26

I have a button that adds dynamic input fields.

This is what I have so far:

<input id="field" matInput formControlName="field">

But for now, this is just static. Let's say we have 3 input fields, then I want the formControlName field to be an array.

In HTML you can do it like this:

<input type="text" name="field[]" value="foo">
<input type="text" name="field[]" value="bar">
<input type="text" name="field[]" value="baz">

How do you do this in Angular?

CodePudding user response:

You can consider declaring the fields as FormArray element from the beginning itself. And you can keep adding the dynamic input fields inside FormArray. Using FormArray you can easily loop over fields.controls array to render field control.

HTML

<form [formGroup]="form">
  <button (click)="addField()">Add Fields</button>
  <div formArrayName="fields">
    <ng-container *ngFor="let field of form.get('fields')?.controls">
      <input type="text" [formControl]="field" value="foo" />
    </ng-container>
  </div>
</form>

TS

addField() {
    const fields = this.form.get('fields') as FormArray;
    fields.push(new FormControl());
    console.log(fields)
}

Working Stackblitz

  • Related