How to return a component to its original state in Angular 2

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

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 back to its original values ​​and also change the variables outside of the form back to their original value. So I want the whole component to return to its original state. I want the component to be reset to its original state after being closed.

+3


source to share


1 answer


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



This brings the state of the form back to its original and unchanged state.

+5


source







All Articles