6

I'm having issue on removing the FormArray from ReactiveForm.

I have the following code :

ngOnInit() {
  this.survey = new FormGroup({
    surveyName: new FormControl(''),
    sections: new FormArray([
      this.initSection(), 
    ]), 
  });      
}

initSection(){
  return new FormGroup({
    sectionTitle : new FormControl(''),
    sectionDescription : new FormControl(''),
  });
}

addSection(){
  const control = <FormArray>this.survey.controls['sections'];
  control.push(this.initSection());
}

Now for deletion the formControl surveyName I just do

this.survey.removeControl('surveyName');

And above code is working fine for surveyName. But what thing i can use for deletion the form array sections. I want to delete the whole section object with key.

2 Answers 2

6

You should always use removeControl to remove both formControl and entire formArray from reactiveform.

Things you have to pay attention is that you should use ngIf to control not showing the removed element after it's removed from reactiveform.

see sample demo.

Sign up to request clarification or add additional context in comments.

11 Comments

Thank you for answer bro. your answer is good. i have passed 2 day on this issue. but i did not solved it. i was doing same but i was not using the nfIf to control showing.
i did it already but i have one more question if i have on level same inside it. then how we will do it?
mean inside the every section i can add multiple questions and in every question i can add multiple options. now i want to delete the options:[{},{}] array.
@MuhammadIrfan they are the same. If you have more problems, just create new questions. :-)
|
3

use removeAt() method for removing the element from formarray

13 Comments

can you tell me the code how ? because i tried a lot on it.
your_array.slice(index, 1);
find the index position you need to delete in array and apply this slice code
what will be index here? my mean i have this.survey.slice(?). because i'm going to remove the whole object sections
are you going to flush all the array elements (or) a particular one
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.