Search code examples
angularformscomponentsresetchildren

Angular 6 nested sub child reactive Form not reset


I have a two level nested FormGroup.

I pass by @Input an FormGroup to the first child component network myForm.get('network').

Inside the component network i pass by @Input a sub FormGroup network?.get('proxy') in another component (proxy component).

code stackblitz

Sample:

this.myForm = fb.group({ 
     id: [null],
     network: fb.group({
       status: [true],
       proxy: fb.group({ enable: [true] })
     })
  })

Summary:

Parent component => myForm

child network component => myForm.get('network') ngOnChanges trigger

sub child proxy component => myForm.get('network')ngOnChanges not trigger

ps: i use on each child the ChangeDetectionStrategy.OnPush.

Probleme:

But i seems when i reset from my parent (myForm) myForm.reset(), he reset just one sub level in network component, but not in the proxy sub child component.

How i could chain this reset from the root tho the sub child ?

I tried pass the formGroup in a observale and async the result, but to complex use it in my all structure.

My idee is:

Call From Network the child proxy with @ViewChild and reset from there but look that weird for me.

Is a better solution ?


Solution

  • You're not getting the reset on the child components due to ChangeDetectionStrategy.OnPush.

    There are two ways of updating the children forms:

    1. Manually calling markForCheck() (emit children a reset has just happened through a Subject/Observable combo)
    2. Updating the @Input of each children on reset()

    Because of the two nested components, I suggest to take option 1 and let the children be responsible to reflect the changes.

    Here is a working example: https://stackblitz.com/edit/angular-pskaws