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?
CodePudding user response:
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
}
CodePudding user response:
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.