2

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

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

what the difference between [formControlName]="i" and formControlName="i"
when you use brakets, Angular evaluate the content between quotes, so [formControlName]="i", angular evaluate the "i" to 0,1,2.., if you write formControlName="i" Angular look for a control in your formControl with the name "i"

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.