【问题标题】:How to Trigger Validate Function on ngOnChanges in validation directive in Angular?如何在 Angular 中的验证指令中触发 ngOnChanges 上的验证函数?
【发布时间】:2018-08-21 14:24:45
【问题描述】:

如何在 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!**
            }
        }
    }

【问题讨论】:

  • 你必须有控制参考才能做到这一点。
  • 如何使用控件引用
  • 你必须以某种方式提供它。我怎么会知道?我什至不知道该指令的上下文。 idownvotedbecau.se/nomcve

标签: angular angular6 angular-validation angular-validator


【解决方案1】:

无论何时调用 validate 函数,我们都将拥有控制权。当 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. 
        }

【讨论】:

    猜你喜欢
    • 2014-08-22
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多