Saturday 2 February 2019

Remove dynamically created form controls in angular

Remove dynamically created form controls in angular


In this topic we will discuss how to remove dynamically generated form controls. Let us understand this with an example. 

At the moment we have just one set of skill related form controls (skillName, experienceInYears & proficiency) 

remove dynamically created form controls in angular 

As soon as, we add another set of skill related form controls, a button with a RED crossshould appear next to each skill form group. 

angular remove dynamic formcontrol from formgroup 

When the button is clicked, the associated set of skill form controls should be removed. 

Here is the  HTML for the DELETE button 

<div class="col-sm-6" *ngIf="employeeForm.get('skills').length>1">
  <button type="button" class="btn btn-danger btn-sm pull-right"
          title="Delete Skill" (click)="removeSkillButtonClick(i)">
    <span class="glyphicon glyphicon-remove"></span>
  </button>
</div>

Code Explanation : 

The following *ngIf expression ensures, the DELETE SKILL button is only displayed if we have more than one skill FormGroup in the skills FormArray 

*ngIf="employeeForm.get('skills').length>1"

When the button is clicked, removeSkillButtonClick(i) method is called. Notice we are passing the loop variable i to the method. This is the index of the FormGroup that we want to remove from the skills FormArray.  

(click)="removeSkillButtonClick(i)"

The title attribute on the button, displays "Delete Skill" tooltip when you hover the mouse pointer over the button 

title="Delete Skill"

To display the red cross on the button, we are using Bootstrap glyphicon and glyphicon-remove classes. 

<span class="glyphicon glyphicon-remove"></span>

If you do not want to display the DELETE button for the first "skills" form group 

how to delete dynamic formgroups in angular 

Then use the following ngIf expression on the <div> element that contains the "DELETE" button. This will ensure that the DELETE button will only be displayed for all the dynamically generated SKILL form groups except the first one. 

<div class="col-sm-6" *ngIf="i>0">

Include the following method in the component class.  

removeSkillButtonClick(skillGroupIndex: number): void {
  (<FormArray>this.employeeForm.get('skills')).removeAt(skillGroupIndex);
}

Code Explanation 
  • Notice we are using the get() on the root form group (employeeForm) and passing it the name of our skills FormArray. 
  • The get() method returns the FormArray as an abstract control
  • To be able to use removeAt() method of the FormArray class, we are type casting the AbstractControl type to FormArray using the type caste operator <FormArray>
  • To the removeAt() method we pass the index of the skill FormGroup we want to remove from the skills FormArray

No comments:

Post a Comment