1

如何在 Angular 中的验证指令中触发 ngOnChanges 上的验证函数?

我检测到 ngOnChanges,但它无法触发验证功能

@Directive({
        selector: '[uppercase]',
        providers: [{
            provide: NG_VALIDATORS,
            useExisting: RdUppercaseDirective,
            multi: true
        }]
    })
    export class RdUppercaseDirective implements Validator, OnChanges  {
        @Input('uppercase') uppercase: any;

        r = new rdValidators;

        validate(control: AbstractControl): {
            [key: string]: any
        } | null {
            let u = this.uppercase === 'false' || this.uppercase === false ? false : true;
            if(!control.value)
            {
                return null;
            }
            if(u === false)
            {
                return null;
            }            
            var result = (/[a-z]/.test(control.value));
            return control.dirty  && control.value ? result ? { 'uppercase' : true } : null : null;
        }

        ngOnChanges(changes: SimpleChanges){
            if(changes.uppercase){
                  //**How to Trigger Validate Function Here!**
            }
        }
    }
4

1 回答 1

0

每当调用验证函数时,我们将拥有控制权。当 Angular 验证表单(默认行为)时,默认情况下将传递此控件。但是,当我们调用 ngOnChanges 中的 validate 函数时,我们需要有 control(AbstractControl) 实例,这样我们可以将参数抽象控件存储在一个私有属性中,我们可以在手动调用时使用它。

@Directive({
    selector: '[uppercase]',
    providers: [{
        provide: NG_VALIDATORS,
        useExisting: RdUppercaseDirective,
        multi: true
    }]
})
export class RdUppercaseDirective implements Validator, OnChanges  {
    @Input('uppercase') uppercase: any;
    private _control: AbstractControl;

    r = new rdValidators;

    validate(control: AbstractControl): {
        [key: string]: any
    } | null {
        this._control = control
        let u = this.uppercase === 'false' || this.uppercase === false ? false : true;
        if(!control.value)
        {
            return null;
        }
        if(u === false)
        {
            return null;
        }            
        var result = (/[a-z]/.test(control.value));
        return control.dirty  && control.value ? result ? { 'uppercase' : true } : null : null;
    }

    ngOnChanges(changes: SimpleChanges){
        if(changes.uppercase){
              //** you can access _control object here to call your validation function 

              this._control.updateValueAndValidity(); 
              //** this will update value and call validation function. 
        }
于 2019-02-28T04:28:34.283 回答