How to add/remove FormControl from a nested FormGroup

╄→尐↘猪︶ㄣ 提交于 2019-12-23 11:55:14

问题


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 address3 to the form group address? And similarly how to remove them from the same FormGroup?


回答1:


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.

So in your case it would be:

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

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



回答2:


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

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):

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!



来源:https://stackoverflow.com/questions/49293093/how-to-add-remove-formcontrol-from-a-nested-formgroup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!