akanzari
akanzari

Reputation: 107

Angular formarray push formcontrol

In my form I need to add companies, i want to save in the database a list of string with the company i added, the problem is that the value of the company in formarray is always empty

<button (click)="addNewCompany()">Add new Company</button><br><br>
<form [formGroup]="myForm">
    <div formArrayName="companies">
        <div *ngFor="let comp of getForm(); let i=index>
            <fieldset>
                <legend>
                    <h3>COMPANY {{i+1}}: </h3>
                </legend>
                <label>Company Name: </label>
                <input formControlName="comp" /><span><button (click)="deleteCompany(i)">Delete Company</button></span>
            </fieldset>
        </div>
    </div><br>
  </form>


export class AppComponent {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      companies: this.fb.array([])
    });
  }

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

  addNewCompany() {
    const control = <FormArray>this.myForm.get("companies");
    control.push(this.fb.control(''));
  }

  deleteCompany(index) {
    let control = <FormArray>this.myForm.controls.companies;
    control.removeAt(index);
  }

}

Stackblitz

Upvotes: 2

Views: 100

Answers (1)

Drenai
Drenai

Reputation: 12357

It's really handy that you added the StackBlitz demo too!

<input [formControlName]="i" />

As the items of the FormArray will have index's 0, 1, 2..., these become the formControlName values. You need to use the [] notation also, otherwise it uses i as a string, instead of using the property value of i, e.g. 0, 1

Upvotes: 1

Related Questions