2

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!'.

tzm
  • 588
  • 1
  • 12
  • 27

1 Answers1

1

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!');
    );
  }
Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
  • 'Form reset done!' displayed in console, nothing is cleared. Maybe the reason why it's happening is because all fields which needs to be cleared are in other components (child components). Thank you for trying to help me ;) – tzm Aug 03 '18 at 13:06
  • @tzm This is the correct approach. If the values being reset are in other components, then each of those components needs to do this. My preferred way to accomplish this is to give each child component a `reset` method, and let that both change the values and then call `.markForCheck()` – Vlad274 Aug 03 '18 at 13:10
  • @Vlad274 When I am trying to reset this values manually (ex. this.epense.name = '') then I am getting validation errors. Is there some option to reset values manually and then clear validation errors? – tzm Aug 03 '18 at 13:17
  • @tzm Seems like the solutions in https://stackoverflow.com/questions/34608361/how-to-reset-form-validation-on-submission-of-the-form-in-angular-2 might be what you're looking for – Vlad274 Aug 03 '18 at 13:26