Reputation: 598
I have some big form which contains multiple child components (values are send to them as @input). After clicking submit button all fields should be cleared (and no validation errors should be displayed). I tried to reset form in couple different ways, but nothing works.
I wrote createForm.reset() or createForm.resetForm() inside .html file
<form #createForm="ngForm" (ngSubmit)="addExpense(createForm.value); createForm.resetForm()">
Second way to do it
.ts
@ViewChild('createForm') formValues;
addExpense(form): void {
this.expenseService.addExpense(this.expense).subscribe(() => {
this.formValues.resetForm();
console.log('Form reset done!');
);
}
.html:
<form #createForm="ngForm" (ngSubmit)="addExpense(createForm.value)">
This also don't reset the form, no errors are displayed. When I looked into console I saw 'Form reset done!'.
Upvotes: 2
Views: 3128
Reputation: 27293
Use ChangeDetectorRef to detect the changes
constructor(private cd:ChangeDetectorRef){
}
@ViewChild('createForm') formValues;
addExpense(form): void {
this.expenseService.addExpense(this.expense).subscribe(() => {
this.formValues.resetForm();
this.cd.markForCheck()
console.log('Form reset done!');
);
}
Upvotes: 1