【问题标题】:re-evaluate custom validator directive on input change重新评估输入更改的自定义验证器指令
【发布时间】:2021-03-31 00:14:45
【问题描述】:

我有一个自定义指令验证器,它使用输入来检查有效性。使用原始值,有效性工作得很好。但是,如果我更新输入,验证器仍然会显示错误并且不会重新评估该值。如何在输入更新时强制重新评估?

指令:

export class TimeRangeValidatorDirective implements Validator {
    @Input() maxTime;
    @Input() minTime;

    validate(control: AbstractControl): ValidationErrors | null {
        return CustomValidators.timeRange(this.maxTime, this.minTime)(control);
    }
}

当最小或最大时间更新时,我想让验证重新运行,这样如果新的最大值高于控制值或新的最小值低于它,以前的错误将不会持续

编辑 基于@Kevin Zhang 给出的答案(为了清楚起见,在此重写)

解决办法:

export class TimeRangeValidatorDirective implements Validator {
    private _onChange?: ()=>void;
    private _maxTime;
    private _minTime;

    @Input() 
    get maxTime() { return this._maxTime}
    
    set maxTime(value) {
        this._maxTime = value;
        if(this._onChange) {
            this._onChange();
        }
    }

    @Input() 
    get minTime() { return this._minTime}
    
    set minTime(value) {
        this._minTime = value;
        if(this._onChange) {
            this._onChange();
        }
    }

    validate(control: AbstractControl): ValidationErrors | null {
        return CustomValidators.timeRange(this.maxTime, this.minTime)(control);
    }

    registerOnValidatorChanges(fn:()=>void): void {
        this._onChange = fn;
    }
}

【问题讨论】:

    标签: angular validation angular-directive


    【解决方案1】:

    请参考下面的代码使用 getter/setter 并注册验证器更改 fn。

    @Directive({
      selector:
          ':not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]',
      providers: [REQUIRED_VALIDATOR],
      host: {'[attr.required]': 'required ? "" : null'}
    })
    export class RequiredValidator implements Validator {
      private _required = false;
      private _onChange?: () => void;
    
      /**
       * @description
       * Tracks changes to the required attribute bound to this directive.
       */
      @Input()
      get required(): boolean|string {
        return this._required;
      }
    
      set required(value: boolean|string) {
        this._required = value != null && value !== false && `${value}` !== 'false';
        if (this._onChange) this._onChange();
      }
    
      /**
       * @description
       * Method that validates whether the control is empty.
       * Returns the validation result if enabled, otherwise null.
       */
      validate(control: AbstractControl): ValidationErrors|null {
        return this.required ? Validators.required(control) : null;
      }
    
      /**
       * @description
       * Registers a callback function to call when the validator inputs change.
       *
       * @param fn The callback function
       */
      registerOnValidatorChange(fn: () => void): void {
        this._onChange = fn;
      }
    }
    

    【讨论】:

    • 你能解释一下onChange函数是什么,如果我使用指令,如何提供它?
    • registerOnValidatorChange 是 Validator 实现的,所以 fn 是回调函数,所以一旦你调用 onChange,它会触发 Angular 知道你在模板上设置的更改。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 2014-03-07
    • 2019-08-29
    • 1970-01-01
    • 2021-01-08
    相关资源
    最近更新 更多