How to mark reactive form as Pristine when patching values into child components?

Viewed 434

I have a complex reactive form that is split up into 3 components (StackBlitz here):

  1. app component: parent, holds logic for adding and deleting, as well as starts functions on init
  2. group-control-component: child of app-component. takes care of group objects in form
  3. condition-form-component: child of group-control-component. takes care of conditions in form within the groups

Here is what a form object looks like, for example:

{
  "groups": [
    {
      "conjunctor": null,
      "conditions": [
        {
          "variable": null
        }
      ],
      "groups": []
    }
  ]
}

I am patching these values from a data.ts object in the stackblitz attached. In real time, this data is coming from a server to patch the values of the form.

Is there a way to set the form to pristine after being patched into the child components? The reason for this, is I am trying to have a "delete" button, where after a form is patched, if the form is still pristine, then the user can delete the data source that it came from. If the form is not pristine, that means they changed something so it's no longer a deletion, but rather an 'update' to the data source.

What has worked so far, is by setting a timeout for the markAsPristine(); function. This works because it waits long enough for the form to patch before setting everything to be pristine. However, I am confident there must be a better way. Is there somehow I can wait until all the child component's values are patched, and then set the form to pristine using this._form.markAsPristine();?

Working code from appcomponent, with timeout for markAsPristine();:

_buildFormFromData() {
  if (data.groups.length) {
    this._addGroup();
  }
  this._form.patchValue(data);

  setTimeout(() => {
    this._form.markAsPristine();
  }, 1000)
}
0 Answers
Related