secondbreakfast
secondbreakfast

Reputation: 4374

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?

Upvotes: 7

Views: 5475

Answers (2)

kaminarifox
kaminarifox

Reputation: 433

Use spread operator

const errors = this.userForm.controls.username.errors || {};
this.userForm.controls.username.setErrors({
  'exists': 'Username already exists', ...errors
})

Upvotes: 3

user4676340
user4676340

Reputation:

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)

Upvotes: 12

Related Questions