Search code examples
angularform-controlformgroups

How use correct markAsDirty on Angular


Please, someone explain to me the correct way to use markAsDirty.

In my example, if the markAsDirty is done on form, the reset on any control change the form to pristine.

Is this expected behavior?

See on https://stackblitz.com/edit/angular-h9gtyf?file=src%2Fapp%2Fapp.component.ts


Solution

  • You need to set option param for reset method, like: form2.get('id2').reset(null, {onlySelf: true});

    The onlySelf option applies the reset() only to that control, not its parent.

    Its default value is false and that's the reason why your form is marked as pristine after the reset of the id2 form control.

    You can check the official angular website: https://angular.io/api/forms/FormControl#reset