Reset FormArray to initial state

1.9k views Asked by At

I have a FormArray with some initial controls in it. The user has an option to add controls by clicking a button which triggers the push() method.

I wanna give the user a cancel button which will reset the form to its initial state, removing all added controls.

As of now I am thinking of two approaches:

Option 1: keep track of the index where the controls were added and use the removeAt() method

Option 2: alternatively, I can just reconstruct the entire FormArray with its initial config.

But is there a simpler way to reset the FormArray to a certain state, something like when we reset the value using setValue() or I have to rebuild it manually using the above options?

1

There are 1 answers

4
Kamran Khatti On BEST ANSWER

To clear all form array values you can use .clear()

here is the complete code will all possible methods (add, remove, reset)

form: FormGroup;

constructor(private fb: FormBuilder) {}

get skills() {
  return this.form.get('skills') as FormArray;
}

newSkill(): FormGroup {
  return this.fb.group({
   skill: '',
   exp: '',
 })
}

addSkill() {
  this.skills.push(this.newSkill());
}

removeSkill(index) {
  this.skills.removeAt(index);
}

resetSkill() {
 this.skills.clear();
}

ngOnInit() {
  this.form = this.fb.group({
   name: [''],
   email: [''],
   skills: this.fb.array([])
 });
}

Template

<form [formGroup]="form">
  Name <input type="text" formControlName="name"> <br>
  Email <input type="text" formControlName="email"> <br>
  <div formArrayName="skills">
   <div *ngFor="let skill of skills.controls; let i=index">
     <div [formGroupName]="i">
       skill name :
       <input type="text" formControlName="skill">
       exp:
       <input type="text" formControlName="exp">

       <button (click)="removeSkill(i)">Remove</button>
     </div>
   </div>
  </div>
  <button type="button" (click)="addSkill()">Add Skill</button>

  <br><br>
  <button type="button" (click)="resetSkill()">Reset Skills</button>
</form>

Working DEMO