How to programmatically append an error to a FormGroup control?

Viewed 1605

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?

2 Answers
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
})
Related