javascript 如何从嵌套的 FormGroup 添加/删除 FormControl

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49293093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:31:18  来源:igfitidea点击:

How to add/remove FormControl from a nested FormGroup

javascriptangular2-forms

提问by Apar Adhikari

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],
      })
    })
  }

How to add a FormControl named address3to the form group address? And similarly how to remove them from the same FormGroup?

如何address3在表单组中添加一个名为 FormControl 的控件address?同样如何从同一个 FormGroup 中删除它们?

回答by Erex

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.

首先,您必须从主 FormGroup 中获取子 FormGroup,然后您可以使用此处文档中引用的 addControl 和 removeControl:https://angular.io/api/forms/FormGroup 。

So in your case it would be:

所以在你的情况下,它将是:

//Add:
this.candidateForm.get('address').addControl('address3',[]);

//Remove:
this.candidateForm.get('address').removeControl('address2', null);

回答by Ali Adravi

I tried Adhikari answer but could not worked for me, it always throw error:

我尝试了 Adhikari 答案,但对我不起作用,它总是抛出错误:

error TS2339: Property 'addControl' does not exist on type 'AbstractControl'.

His answer helped me to think, and finally I came out with this:

他的回答帮助我思考,最后我得出了这个:

Write a getter property anywhere like this (to get the group):

在任何地方编写一个 getter 属性(以获取组):

get addressGroup() { return this.candidateForm.get('address'); }

Now wherever you want to add some controls, use like this:

现在,无论您想在何处添加一些控件,都可以像这样使用:

if(this.addressGroup instanceof FormGroup){
   var ctrl:AbstractControl = this.fBuilder.control('', [Validators.required]);
   (<FormGroup>this.addressGroup).addControl('address3', ctrl);

   var emailCtrl:AbstractControl = this.fBuilder.control('', [Validators.email]);
   (<FormGroup>this.addressGroup).addControl('myEmail', emailCtrl);

   var add4:AbstractControl = this.fBuilder.control('', []);
   (<FormGroup>this.addressGroup).addControl('address4', add4);
}

It is an old question, but hope this will help someone!

这是一个老问题,但希望这会对某人有所帮助!