In my dynamic FormGroup I would like to programmatically append an error to a form control, but the only way I see to add an error is like this
this.userForm.controls.username.setErrors({
'exists': 'Username already exists'
});
Which completely replaces any existing errors. Is there any way to append a single error to a dynamic FormGroup control?
control.setErrors({ ...(control.errors || {}), 'newError': 'text of the error' })
You just have to get the previous errors and spread them into your new error object.
control.errors || {}
Is a protection against non-spreadable values (for instance, undefined or null)
Use spread operator
const errors = this.userForm.controls.username.errors || {};
this.userForm.controls.username.setErrors({
'exists': 'Username already exists', ...errors
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With