Angular 8中的自定义验证

问题描述 投票:0回答:1

我想通过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; } }

angular
1个回答
0
投票
要构建验证器,将required属性放在表单控件上是不够的。您需要通过实现Validator接口并为其提供NG_VALIDATORS令牌来检查其自身的有效性:
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.