本文介绍了如何从嵌套的 FormGroup 添加/删除 FormControl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
candidateForm:FormGroup;
constructor(private fBuilder: FormBuilder){ }
ngOnInit(){
this.candidateForm = this.fBuilder.group({
fname: [null, [Validators.required]],
lname: [null, [Validators.required]],
address: this.fBuilder.group({
address1: [null],
address2: [null],
})
})
}
如何将名为address3
的FormControl添加到表单组address
?同样如何从同一个 FormGroup 中删除它们?
How to add a FormControl named address3
to the form group address
? And similarly how to remove them from the same FormGroup?
推荐答案
首先,您必须从主 FormGroup 中获取子 FormGroup,然后您可以使用此处文档中引用的 addControl 和 removeControl:https://angular.io/api/forms/FormGroup.
First you have to get the sub FormGroup from your main FormGroup, and then you could use the addControl and removeControl refrenced in the documentation here: https://angular.io/api/forms/FormGroup.
所以你的情况是:
//Add:
this.candidateForm.get('address').addControl('address3',[]);
//Remove:
this.candidateForm.get('address').removeControl('address2');
这篇关于如何从嵌套的 FormGroup 添加/删除 FormControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!