Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 reactive forms delete error

Tags:

I´m trying to set a form control status to valid

this.currencyForm.controls['currencyMaxSell'].setErrors({smallerThan: true}) 

now I want delete this error.

like image 291
Arman Gevorgyan Avatar asked Apr 17 '17 04:04

Arman Gevorgyan


People also ask

How to disable validation in Angular?

Angular tells you that it's better for you to use the ways it gives you to disable/enable form controls. You can enable/disable a form control by using the following ways: Instantiate a new FormControl with the disabled property set to true. FormControl({value: '', disabled: true}) .

Why use Reactive forms Angular?

Reactive forms provide access to information about a given control through properties and methods provided with each instance. These properties and methods of the underlying AbstractControl class are used to control form state and determine when to display messages when handling input validation.


2 Answers

Other solutions seem to not work. It looks like angular thinks the control is invalid as long as the errors property is not null.

As long as you want to remove just a single error and leave others there's no way to do it but manually. This function will remove only one error specified in the argument and leave others. It will also make sure that if you remove the last error the control will become valid.

// call it in validator function if control is valid removeError(this.currencyForm.controls['currencyMaxSell'], 'smallerThan');  // this function removes single error function removeError(control: AbstractControl, error: string) {   const err = control.errors; // get control errors   if (err) {     delete err[error]; // delete your own error     if (!Object.keys(err).length) { // if no errors left       control.setErrors(null); // set control errors to null making it VALID     } else {       control.setErrors(err); // controls got other errors so set them back     }   } }  // this function adds a single error function addError(control: AbstractControl, error: string) {   let errorToSet = {};   errorToSet[error] = true;   control.setErrors({...control.errors, ...errorToSet}); } 
like image 138
karoluS Avatar answered Oct 29 '22 17:10

karoluS


To remove only one form control error when performing manual validation, do the following:

this.myFormGroup.get('myControl').setErrors({'myCustomError':null}) 

This will only update the value for the specified error, and will not erase any previous validation you may have done, as opposed to setErrors(null), which nullifies the whole errors object for the control.

like image 20
bedranfleck Avatar answered Oct 29 '22 17:10

bedranfleck