Home > Software engineering >  Angular's template-driven form reset is not working using component class
Angular's template-driven form reset is not working using component class

Time:05-20

Component Template

<form #formGroupContactUs_Template = "ngForm" (ngSubmit)="contactUsTemplateSubmit()">        
       <input type="text"  name="name" [(ngModel)]="model.name">
       <!-- {{name!.value}} -->
       <button  type="submit" 
       [disabled]="this.formGroupContactUs_Template.status != 'VALID'">Submit</button>
       <a  (click)="clearAll()">Clear All</a>
    </form>

Component Class

export class TemplateComponent implements OnInit {
 
  constructor() { }

  ngOnInit(): void {
  }

  model: any = {};

  contactUsTemplateSubmit() {
    console.log(this.model); //form Values
  }

  clearAll() {
    this.model.reset(); // not working
  }

}

CodePudding user response:

For programmatic approach you could get the form in ngAfterViewInit() and call reset on it. https://stackoverflow.com/a/52167560/15439733

Or on template this would work too.

   <a  (click)="formGroupContactUs_Template.reset()">Clear All</a>

Working example: https://stackblitz.com/edit/angular-workbench-template-driven-form-btfxnf?file=src/app/app.component.html

CodePudding user response:

OK, here is solution for clearing the form

in .ts

 clearAll(InputFormValue: ngForm) {
   InputFormValue.form.reset();//this will work
  }

in .html

<form #formGroupContactUs_Template="ngForm" (ngSubmit)="contactUsTemplateSubmit(formGroupContactUs_Template)">        
       <input type="text"  name="name" [(ngModel)]="model.name">
       <!-- {{name!.value}} -->
       <button  type="submit" 
       [disabled]="this.formGroupContactUs_Template.status != 'VALID'">Submit</button>
       <a  (click)="clearAll()">Clear All</a>
    </form>
  • Related