How can I reset Angular Reactive Form
In Angular 8, if you do
<form #form="ngForm" (ngSubmit)="process(form)">
process(form: NgForm) { ...
You'll get the following error when you build with --prod
Argument of type 'FormGroupDirective' is not assignable to parameter of type 'NgForm'.
on (ngSubmit)
What I did was to inject form
template reference as FormGroupDirective
then call resetForm()
.
<form #form (ngSubmit)="process(form)">
@ViewChild('form', { static: false }) FormGroupDirective formDirective;
See FormGroupDirective
Almost ! Use a reactive form for that :
<form [formGroup]="myForm">
<mat-form-field class="full-width">
<input matInput placeholder="Weather" formControlName="weather">
</mat-form-field>
</form>
<button mat-raised-button (click)="myForm.reset()">Reset</button>
export class Example{
myForm: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm = fb.group({
weather: ''
});
}
// If the HTML code doesn't work, simply call this function
reset() {
this.myForm.reset();
}
}
<form [formGroup]="thisIsAForm" (ngSubmit)="onSubmit()">
<mat-form-field class="full-width">
<input formControlName="weather" placeholder="Weather">
</mat-form-field>
</form>
<button mat-raised-button (click)="resetForm()">Reset</button>
export class Example{
thisIsAForm: FormGroup;
constructor() {
this.thisIsAForm = new FormGroup(
weather: new FormControl('')
);
}
resetForm() {
this.thisIsAForm.reset();
}
}