简体   繁体   中英

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. 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. I want to remove the formGroup, how can i do that?

i am able to remove the formControl inside the formGroup like this

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

but not know how to remove the formGroup itself UPDATE 1

i did something like this, just let me know if this is right var formControls=this.form.controls; delete formControls.someGroup;

In your example this.form is FormGroup by itsself. someGroup is just this.form 's control (each form group may have another form groups as its child controls). FormGroup has removeControl() function, which looks like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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