简体   繁体   中英

Angular Template-Driven form reset programmatically

I'm new to Angular/Typescript and currently using a Template-Driven form in Angular 10. I'm trying to reset the form without submitting it and without clicking a button. I've checked out similar issues but they all rely on submitting the form in order to reset it. I keep getting the error:

ERROR TypeError: Cannot read property 'reset' of undefined

Below is my TS file code:

@ViewChild('visitorForm', { static: true }) visitorForm: NgForm;

constructor(private myService: MyService)
{
  this.myService.imagePosted.subscribe(
    userDetails => {
      this.userDetails = userDetails;
     this.visitorForm.reset();
    }
  );
}

And here is my component.html:

<form (ngSubmit)="onSubmit(visitorForm)" #visitorForm="ngForm">
  <div class="row">
    <div class="col-md-10 form-group">
        <input 
        [ngModel]="visitor.firstName"
        required 
        type="text" 
        id="firstName" 
        name="firstName" 
        placeholder="First Name" 
        class="form-control"
        #firstName="ngModel">
    </div>
  </div>
</form>

I can clear the form on submit or if I use a button with an event binded to it, but that's not what I'm looking for. I want to be able to reset the form within the subscribe above. Does anyone know how to do this?

Move the code to ngAfterViewInit() so the reference to the form exists and then try with resetForm():

https://angular.io/guide/lifecycle-hooks

https://angular.io/guide/forms

Stackblitz demo of template-driven form reset using different methods:

https://stackblitz.com/edit/angular-workbench-template-driven-form

Be careful with the sintax as it is very tricky: :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM