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

问题描述 投票:3回答:2
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中删除它们?

javascript angular2-forms
2个回答
6
投票

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

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

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

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

1
投票

我尝试过Adhikari的答案,但无法为我工作,它总是抛出错误:

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

他的回答让我思考,最后我出来了:

在这样的任何地方写一个getter属性(获取组):

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

现在,无论您想要添加一些控件,请使用如下所示:

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);
}

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

© www.soinside.com 2019 - 2024. All rights reserved.