简体   繁体   English

如何从angular4的表单中删除formGroup?

[英]How to remove a formGroup from form in angular4?

I am using template driven forms and i want to remove a formGroup from the form controls. 我正在使用模板驱动的表单,并且想从表单控件中删除formGroup。 how can i do that? 我怎样才能做到这一点? i have following controls in my form 我的表单中有以下控件

在此处输入图片说明

as you can see in this image, i have a set of formControls and a formGroup. 如您在此图像中看到的,我有一组formControls和一个formGroup。 I want to remove the formGroup, how can i do that? 我想删除formGroup,我该怎么做?

i am able to remove the formControl inside the formGroup like this 我能够像这样在formGroup内删除formControl

const ymmtGroup = <FormGroup>this.form.controls['someGroup'];
ymmtGroup.removeControl('someControl');

but not know how to remove the formGroup itself UPDATE 1 但不知道如何删除formGroup本身UPDATE 1

i did something like this, just let me know if this is right var formControls=this.form.controls; 我做了这样的事情,只是让我知道这是否正确var formControls = this.form.controls; delete formControls.someGroup; 删除formControls.someGroup;

In your example this.form is FormGroup by itsself. 在您的例子this.formFormGroup通过itsself。 someGroup is just this.form 's control (each form group may have another form groups as its child controls). someGroup只是this.form的控件(每个窗体组可能有另一个窗体组作为其子控件)。 FormGroup has removeControl() function, which looks like: FormGroup具有removeControl()函数,如下所示:

  removeControl(name: string): void {
    if (this.controls[name]) this.controls[name]._registerOnCollectionChange(() => {});
    delete (this.controls[name]);
    this.updateValueAndValidity();
    this._onCollectionChange();
  }

and which you already used. 以及您已经使用过的 So, just try: 因此,只需尝试:

this.form.removeControl('someGroup');

Try something like this: 尝试这样的事情:

Proper Way to remove a form Group 删除表格组的正确方法

export class AppComponent  {
  myForm: FormGroup;

  constructor(private fb: FormBuilder){
    this.createForm();
    this.removeGroup();
    console.log(this.myForm.value)

  }

  createForm(){
    this.myForm = this.fb.group({
      parentGroup: this.fb.group({
        childGroup: this.fb.group({
          control1: null,
          control2:null,
          control3:null
        })
      })
    })
  }

  removeGroup(){
    this.myForm.removeControl('parentGroup');
    this.myForm.updateValueAndValidity();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM