示例:
在模板中添加错误消息指令:
在指令中显示错误消息:
import { Directive, HostBinding, HostListener } from '@angular/core';
@Directive({ selector: '[appErrorMessage]' }) export class ErrorMessageDirective { @HostBinding('class.error-message') hasErrorMessage = true;
constructor() { }
@HostListener('input', ['$event.target']) onInput(target: HTMLInputElement) { const control = target.validity;
if (control.valid) {
this.hasErrorMessage = false;
} else {
this.hasErrorMessage = true;
}
} }
在ngModel或FormControl中设置错误消息:
ngOnInit() { this.myForm = new FormGroup({ name: new FormControl('', [ Validators.required, Validators.minLength(4) ]), email: new FormControl('', [ Validators.required, Validators.pattern('[^ @]@[^ @]') ]) }); }
get name() { return this.myForm.get('name'); }
get email() { return this.myForm.get('email'); }
getErrorMessage(control: AbstractControl) {
return control.hasError('required') ? 'You must enter a value' :
control.hasError('email') ? 'Not a valid email' :
control.hasError('minlength') ? Must be at least ${control.errors.minlength.requiredLength} characters
:
'';
}