Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set component back to initial state in Angular 2

Tags:

I have a component that is a modal which has a form and some other variables outside of that form. The component is something like this:

The component:

export class PersonComponent implements OnInit { 

countPerson: number=0;
persons: Person [] = [];

personForm : FormGroup;

ngOnInit(){
  this.step1Form= this.fb.group({
     firstName: 'Levi',
     lastName:  'Ackerman'
  });
}

submitPerson(person: Person){
  this.persons.push(person);
  this.incrementPerson();
}

incrementPerson(){
  this.count++;
}

}

In the template:

 <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body>
         <label>First Name</label>
         <input type="text" formControlName="firstName">
         <label>LastName Name</label>
         <input type="text" formControlName="lastName">
         <button type="button" (click)="submitPerson()">Submit</button>
      </div>
     <div class="modal-footer">
         <button type="button" data-dismiss="modal">Close</button>
     </div>
   </div> 
</div>

I want to reset the form controls back to initial values and as well set the variables outside of the form back to initial value. So basically I want the whole component be back to initial state. I want the component be reset to initial state once closed.

like image 833
ilovejavaAJ Avatar asked Apr 17 '17 19:04

ilovejavaAJ


1 Answers

If there is a form on your HTML (not shown in the provided snippet) you can use the reset method on the form: this.yourFormName.reset()

This resets the form state back to pristine and unchanged.

like image 73
DeborahK Avatar answered Sep 21 '22 10:09

DeborahK