编辑 2
正如Alex和官方文档所说,Angular 5.0.0 版为您的 ngModel 提供了新选项updateOn: 'blur'
this.email = new FormControl(null, {
validators: Validators.required,
updateOn: 'blur'
});
您还可以使用其他更新选项:(change
默认)blur
、、、submit
。
原来的
我使用指令删除焦点上的整个验证并在模糊事件后将其返回。它基于克里斯蒂安·德尚的回答。
我仅在模糊时更新有效性,因此如果值在焦点之前无效,则在之后将无效。但如果你开始输入,有效性将被更新。
由于某些原因,清除顺序是有意义的,所以我先清除异步验证器。
任何提供的建议都会有所帮助 =)
import { Directive } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[validate-onblur]',
host: {
'(focus)': 'onFocus($event)',
'(blur)': 'onBlur($event)'
}
})
export class ValidateOnBlurDirective {
private validators: any;
private asyncValidators: any;
constructor(public formControl: NgControl) {
}
onFocus($event) {
this.validators = this.formControl.control.validator;
this.asyncValidators = this.formControl.control.asyncValidator;
this.formControl.control.clearAsyncValidators();
this.formControl.control.clearValidators();
}
onBlur($event) {
this.formControl.control.setAsyncValidators(this.asyncValidators);
this.formControl.control.setValidators(this.validators);
this.formControl.control.updateValueAndValidity();
}
}
另外,请继续关注这个关于 onBlur 验证的Angular 2 github 线程
编辑 1
还有另一个问题 - 如果我只是点击该字段并在点击离开后 - 将调用验证。如果您有任何关于它的通知(或服务器调用) - 它会在您每次执行时出现。所以你可以添加wasChanged
属性并像这样使用它:
@Directive({
selector: '[validate-onblur]',
host: {
'(focus)': 'onFocus($event)',
'(blur)': 'onBlur($event)',
'(keyup)': 'onKeyup($event)',
'(change)': 'onChange($event)',
'(ngModelChange)': 'onNgModelChange($event)'
}
})
export class ValidationOnBlurDirective {
private validators: any;
private asyncValidators: any;
private wasChanged: any;
constructor(public formControl: NgControl) {
}
onFocus($event) {
this.wasChanged = false;
this.validators = this.formControl.control.validator;
this.asyncValidators = this.formControl.control.asyncValidator;
this.formControl.control.clearAsyncValidators();
this.formControl.control.clearValidators();
}
onKeyup($event) {
this.wasChanged = true; // keyboard change
}
onChange($event) {
this.wasChanged = true; // copypaste change
}
onNgModelChange($event) {
this.wasChanged = true; // ng-value change
}
onBlur($event) {
this.formControl.control.setAsyncValidators(this.asyncValidators);
this.formControl.control.setValidators(this.validators);
if (this.wasChanged)
this.formControl.control.updateValueAndValidity();
}
}