1

This is not a debugging problem, we're looking for the conceptual guidance on the best possible solution for the problem

In our Angular 2 app, we've a

  • <parent-component> which has a <form>
  • The <form> has <level-1-child>
  • The <level-1-child> has <level-2-child>
  • The <level-2-child> has <textarea>

What we need to do?

  • Reset the <form> elements of <parent-component>, <level-1-child> & <level-2-child> on <button> click or submit of <parent-component>'s <form>

Here is the issue re-producible

Zameer Ansari
  • 28,977
  • 24
  • 140
  • 219

1 Answers1

2

Without FormBuilder it's harder to do an actual reset, but you can do something like:

Parent component:

<form>
  <level-1 [val]="myVal"></level-1>
</form>

Level 1:

<level-2 [val]="val"></level-2>

Level 2:

<textarea [(ngModel)]="val.someProp"></textarea>

Then simply add @Input() val: any to the level-1 and level-2 components.

So when you "reset" you will reset the myVal object to its original values. This will then take effect on the children as well.

Sidenote: I'm unsure if you have to update the object reference as well for it to take effect but you can then do that with this.myVal = Object.assign({}, this.myVal) should you need it.

You should also call resetForm on the <form> tag when you submit. So something like:

<form #form="ngForm" (ngSubmit)="save()"></form>

@ViewChild('form') form;

save(): void {
  this.form.resetForm()
}

EDIT:

With FormBuilder you'd do:

Parent component:

public form: FormGroup = this.fb.group({
  someProp: ''
});

<form [formGroup]="form">
  <level-1 [val]="form"></level-1>
</form>

Level 1:

<level-2 [val]="val"></level-2>

Level 2:

<div [formGroup]="val">
  <textarea formControlName="someProp"></textarea>
</div>

And then reset the form with this.form.reset().

Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175