required
属性放在表单控件上是不够的。您需要通过实现Validator
接口并为其提供NG_VALIDATORS
令牌来检查其自身的有效性:我想通过Angular 8中的指令实施自定义验证(必需/模式/禁用)
enter code here<input type="text"
custom-data-annotation
[(ngModel)]="someValue"
name="userName" />
我已创建指令
`@Directive({选择器:“ [custom-data-annotation]”})
导出类CustomDataAnnotationDirective实现AfterViewInit,OnInit {
constructor(public el: ElementRef,
private _renderer: Renderer2,
private route: ActivatedRoute) {
}
ngAfterViewInit() {
}
ngOnInit() {
this._renderer.setAttribute(this.el.nativeElement, 'required', 'true');
}
}`
<<我想通过Angular 8中的指令实施自定义验证(必填/模式/禁用),请在此处输入代码
] >>
required
属性放在表单控件上是不够的。您需要通过实现Validator
接口并为其提供NG_VALIDATORS
令牌来检查其自身的有效性:@Directive({
selector: "[custom-data-annotation]",
providers: [
{
provide: NG_VALIDATORS,
useExisting: CustomDataAnnotationDirective,
multi: true
}
]
})
export class CustomDataAnnotationDirective implements OnInit, Validator {
constructor(private _el: ElementRef, private _renderer: Renderer2) {}
ngOnInit() {
this._renderer.setAttribute(this._el.nativeElement, "required", "true");
}
validate(control: AbstractControl): { [key: string]: any } | null {
return !control.value ? { required: true } : null;
}
}
required
属性放在表单控件上是不够的。您需要通过实现Validator
接口并为其提供NG_VALIDATORS
令牌来检查其自身的有效性: