Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically append an error to a FormGroup control?

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?

like image 805
secondbreakfast Avatar asked Jul 17 '26 11:07

secondbreakfast


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
})
like image 40
kaminarifox Avatar answered Jul 20 '26 00:07

kaminarifox