Search code examples
angularangular-reactive-forms

View not updating when form data changes


I have a StackBlitz demo here which shows the issue: https://stackblitz.com/edit/demo-nested-forms

If you wait 2 seconds, the form gets populated by an observable, and you can see the form data as JSON below the coloured blocks. If you change the text in either of the inputs and click off them, you can see the form data gets updated.

If you then click the "Get new form data" button, it calls the same observable to return the initial object again. This time, although the form data gets correctly "reset" the view is not updated.

Any ideas why the view is now out of sync?


Solution

  • You're not applying the formControlName to the control itself, you're setting the value of the text area via the [value] attribute. So it updates first time, but then never receives the updates via the form.

    The fix is to pass the form control name into the child and apply it to the control. If you're doing this, you also need to apply the [formGroup] directive in the same component as the form control name, so you'll need to pass that in too.

    Original version

    child.html

    <div>
      <textarea [value]="value">
      </textarea>
    </div>
    

    parent.html

    <div [formGroup]="form">
      <child formControlName="details" [value]="value">
      </child>
    </div>
    

    Updated version

    child.html

    <div [formGroup]="myFormGroup">
      <textarea [formControlName]="myFormControlName">
      </textarea>
    </div>
    

    child.ts

    @Input() myFormControlName: string;
    @Input() myFormGroup: FormGroup;
    

    parent.html

    <div>
      <child [myFormGroup]="form" myFormControlName="details">
      </child>
    </div>
    

    I've used input property names that are disambiguated from the form directive names. Obviously you would want to use slightly more sensible names.

    Forked stackblitz: https://stackblitz.com/edit/demo-nested-forms-wplzbq

    I have broken the change handling in the process of forking your stackblitz. But the most important thing is that the values are being updated.