It's really clear how to set custom errors in angular:
this.form.controls['field'].setErrors({same:true});
But it is not clear on how to remove that. Anyone know how to do this? Any alternatives?
只需将错误设置为空
this.form.controls['field'].setErrors(null);
this.form.controls['field'].updateValueAndValidity();
this is the method documentation:
/**
* Re-calculates the value and validation status of the control.
*
* By default, it will also update the value and validity of its
ancestors.
*/
updateValueAndValidity({onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}): void {... }
You can use the following when you want to remove the custom error:
delete this.form.controls['field'].errors['same']
you might need/want to update the validity after this with:
this.form.controls['field'].updateValueAndValidity();
您可以使用以下行删除自定义错误。
this.form.controls['field'].updateValueAndValidity();
you can use the below-mentioned method and pass control name, key means error name and value will be true or null to set or remove the error from the controls respectively.
errorInFields(control: AbstractControl,key,value){
let errors = control.errors;
if(!errors){
if(value == null){
control.setErrors(null);
}else{
let error = {};
error[key] = value;
control.setErrors(error);
}
}else{
if(value == null){
if(errors.hasOwnProperty(key)){
delete errors[key];
}
let errorsKey = Object.getOwnPropertyNames(errors);;
if(errorsKey.length <= 0){
control.setErrors(null);
}else{
control.setErrors(errors);
}
}else{
errors[key] = value;
control.setErrors(errors);
}
}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.