natyus
natyus

Reputation: 647

how to acess formcontrols inside formarray in angular

I have the following form:

 form = this.builder.group({
  form2: this.builder.array([
      this.builder.group({
    name: new FormControl(),
    surname: new FormControl(),

  })
]),
  });

in my oninit I am doing this to set one formcontrol with a setvalue

 this.form.controls.personNameField.setValue(this.person.name);

But this does not work, probably due to the controls being inside an formarray. But how can I access my formarray controls?

Upvotes: 1

Views: 1404

Answers (2)

AVJT82
AVJT82

Reputation: 73387

You can reach your form control with the following:

ngOnInit() {
  (this.form.get('form2') as FormArray).at(0).patchValue({ name: 'test' });
}

So we get the formarray inside the parent group, then get the first formgroup in the formarray (at index 0) and patch the value for the name formcontrol.

Upvotes: 0

Haris Bouchlis
Haris Bouchlis

Reputation: 2566

You can add controls with values in a FormArray like this:

get form2Array(){
  return this.form.controls.form2 as FormArrray;
}

// If form control exists at index
addPerson(index: number, person: any){
  const personFormGroup = this.form2Array.at(index) as FormGroup
  personFormGroup.setValue(person) //handle according to your code
}

// If form control does not exist at index
addPerson(index: number, person: any){
  this.form2Array.at(index).setControl(index, this.builder.group({
    name: this.builder.control({}),
    surname: this.builder.control({}),
  }))
  const personFormGroup = this.form2Array.at(index) as FormGroup
  personFormGroup.setValue(person) //handle according to your code
}

Upvotes: 1

Related Questions