1

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?

2
  • You could try making a nested call to access your control, ie. form.controls['form.someControlName']. And on a different note, you'll want to look into setValue vs patchValue. Using the former requires you to provide all FormControls entries in that FormGroup while the latter enables you to patch single values. Commented Nov 26, 2021 at 8:11
  • Thanks how do I have to change it in my html? I tried something like this: <form [formGroup]="form[form2]">. But it says TypeError: Cannot read properties of undefined (reading 'form2.name' Commented Nov 26, 2021 at 8:16

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

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.