: , . . , , , . ntvFormValidity , ng-invalid.
: <input type="number" formControlName="num" placeholder="0" ntvFormValidity>
:
import { Directive, Host, Self, ElementRef, AfterViewInit } from '@angular/core';
import { FormControlName, FormControl, Validators } from '@angular/forms';
@Directive({
selector: '[ntvFormValidity]'
})
export class NtvFormControlValidityDirective implements AfterViewInit {
constructor(@Host() private cn: FormControlName, @Host() private el: ElementRef) { }
ngAfterViewInit() {
var control: FormControl = this.cn.control;
const ntvValidator = () => !this.el.nativeElement.validity.valid ? { error: "invalid" } : null;
const v_fn = control.validator;
control.setValidators(v_fn ? Validators.compose([v_fn, ntvValidator]) : ntvValidator);
setTimeout(()=>control.updateValueAndValidity(), 0);
}
}
, ElementRef FormControl, . @ViewChild, - . , , ElementRef.
Safari HTML Angular , "abc".
, , , , CVA , HTML.
- :
<my-input-number formControlName="num" placeholder="0">
PS: If there is a better way to get a FormControl for a directive, I suppose using Dependency Injection and providersin the declaration, please let me know so that I can update my directive (and this answer).
source
share