Angular 的模板驱动表单重置无法使用组件 class

Angular's template-driven form reset is not working using component class

组件模板

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

组件Class

export class TemplateComponent implements OnInit {
 
  constructor() { }

  ngOnInit(): void {
  }

  model: any = {
    name: "",
  };

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

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

}

对于编程方法,您可以在 ngAfterViewInit() 中获取表单并对其调用重置。

或者在模板上也可以。

   <a class="btn btn-secondary" (click)="formGroupContactUs_Template.reset()">Clear All</a>

工作示例:https://stackblitz.com/edit/angular-workbench-template-driven-form-btfxnf?file=src%2Fapp%2Fapp.component.html

好的,这是清除表单的解决方案

在.ts

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

在.html

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