如何从嵌套FormGroup中添加/删除FormControl [英] How to add/remove FormControl from a nested FormGroup

查看:569
本文介绍了如何从嵌套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:

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

这篇关于如何从嵌套FormGroup中添加/删除FormControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆