[英]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在我的 oninit 中,我这样做是为了设置一个带有 setvalue 的 formcontrol
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?
但是如何访问我的 formarray 控件?
You can add controls with values in a FormArray
like this:您可以像这样在
FormArray
中添加具有值的控件:
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
}
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.所以我们在父组中获取formarray,然后获取formarray中的第一个formgroup(在索引0处)并修补
name
formcontrol的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.