Adding Custom Errors on ngModel

Create Angular project from scratch with Webpack

Have you ever wondered, How to add your own custom errors on ngModel?

If we do that, then no need for an extra check for submitting the form. Since form will be marked as invalid, if any of its ngModel is invalid.

We can make use of the setErrors function which exist on ngModel’s control

Example to set errors

const customError = { badFeeling: true };  
this.feelingNgModel.control.setErrors(customError);  

Example to remove the error

if (this.feelingNgModel.control.hasError('badFeeling')) {  
	delete this.feelingNgModel.control.errors?.badFeeling;  
	this.feelingNgModel.control.updateValueAndValidity();  
}  

In order to remove the error, we need to make sure that the control has error and also notify angular about the change using updateValueAndValidity.

I hope the angular team should also provide the removeError function to do this easily.

Here is a stackblitz example

Comments