Angular 5 FormGroup reset doesn't reset validators
Perform a direct reset on every FormControl
within your FormGroup
to erase values and re-mount validators. This method honors form validation schema post-reset.
Conquer the validation beast
If you're trying to reset your FormGroup
, remember that calling the simple reset()
method won't scrub the errors of the form's validators. Unless explicitly handled, they might continue to lurk around, haunting your page beyond reset. To put a stake through their heart, use:
If you're conjuring custom validation, make sure to reignite validation checks post-reset by calling setValidators()
and updateValueAndValidity()
:
Sweep away the Material error dust
If you've reset the form and your <mat-error>
components are still showing the dusty footprints of your controls, your validators' internal state likely isn't reset. To wipe clean those last pesky footprints, use:
This resetForm()
method does the full cleaning service, going beyond a simple FormGroup.reset()
, by resetting form's state and validity.
Revive your validators from the ashes
After the reset, you'll want to give life back to the validation for required fields. This can be accomplished by looping through all form controls and attaching necessary validators:
Mastering the state with FormGroupDirective
An often overlooked tool in managing form state and validity in Angular is the FormGroupDirective
. Ooo...am I gonna say this? Yes, you can even use it to reset validators.
This directive does a deep clean of the form's state, validity and more importantly treats any persisting 'ng-invalid'
issues.
Banishing validator errors: Your Survival Guide
Even after you've reset your form, die-hard validator errors might continue to exist. These ghosts of validators past can cause quite a stir with lingering error messages. Here's your go-to exorcism chant:
Forum talks and GitHub gossips
Rest easy, you're not alone battling form reset ghosts in Angular. You might find useful incantations and discussions on GitHub, with enough spells to add to your wizard's grimoire.
Was this article helpful?