角度自定义验证指令 - 错误的行为不符合预期

问题描述 投票:1回答:1

我尝试在Angular 7.0.5中编写自定义验证器,但我无法获取并显示错误。

试图调试代码并搜索谷歌和stackoverflow的答案或提示。

在我使用的模板下面:

<form #formWithDirective="ngForm" name="formWithDirective">
  <input ngModel #desiredWithDirective="ngModel" inFuture="2018-04-27"
    type = "date"
    name = "desiredWithDirective">
  <div *ngIf="desiredWithDirective.errors?.future">
    {{ desiredWithDirective.errors | json }}
  </div>
</form>

指令:

import { Directive, forwardRef, Input } from '@angular/core';
import { Validator, AbstractControl, ValidationErrors, NG_VALIDATORS } from '@angular/forms';
import { MyValidators } from './my-validators';

@Directive({
  selector: '[ngModel][inFuture],[formControl][inFuture],[formControlName][inFuture]',
  providers: [{
    provide: NG_VALIDATORS,
    useExisting: forwardRef(() => FutureDirective),
    multi: true
  }]
})
export class FutureDirective implements Validator {
  @Input()
  inFuture: string;

  constructor() { }

  validate(control: AbstractControl): ValidationErrors | null {
    let date: Date;
    if (this.inFuture !== '') {
      date = new Date(this.inFuture);
    }

    return MyValidators.isFuture( date )( control );
  }

  registerOnValidatorChange?(fn: () => void): void;
}

并且inFuture函数的实际实现:

import { ValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';

export class MyValidators {
  static readonly isFuture: (condition?: Date) => ValidatorFn
    = (condition?: Date): ValidatorFn => (control: AbstractControl): ValidationErrors | null => {
      if (control.value === null || control.value === '') {
        return null;
      }

      const selectedDate = new Date(control.value);
      const currentDate = (condition == null) ? new Date() : condition;
      const isFuture = selectedDate > currentDate;

      return isFuture
        ? null
        : { 'future': { currentDate, selectedDate } };
    }
}

如果我选择过去的日期,我预计会显示错误。但是没有显示错误。如果我调试代码并在chrome控制台中执行MyValidators.isFuture( date )( control );,我会收到以下错误:

Uncaught ReferenceError: MyValidators is not defined
    at eval (eval at push../src/app/my-validators/future.directive.ts.FutureDirective.validate (future.directive.ts:25), <anonymous>:1:1)
    at FutureDirective.push../src/app/my-validators/future.directive.ts.FutureDirective.validate (future.directive.ts:25)
    at forms.js:792
    at forms.js:608
    at Array.map (<anonymous>)
    at _executeValidators (forms.js:608)
    at forms.js:573
    at forms.js:608
    at Array.map (<anonymous>)
    at _executeValidators (forms.js:608)

任何关于如何解决这个问题的提示都将不胜感激。

angular angular2-directives
1个回答
1
投票

好吧,我没有改变这个stackblitz中的任何东西,它工作正常,但在调用该函数时仍然给出相同的控制台错误。因为你没有分享你的ngModule:你不是只是忘记申报你的指令吗?

© www.soinside.com 2019 - 2024. All rights reserved.