在输入更改时重新评估自定义验证器指令

re-evaluate custom validator directive on input change

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

指令:

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;
    }
}

请参考下面的代码使用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;
  }
}