【问题标题】:A validator directive is capturing the old input value instead of the new one验证器指令正在捕获旧输入值而不是新输入值
【发布时间】:2021-10-08 06:55:34
【问题描述】:

每当我的dateStart 输入字段发生如下更改时,我都会尝试触发验证:

mycomponent.component.html

<input name="dateStart" type="text" 
       [(ngModel)]="contract.startDate" 
       (ngModelChange)="onStartDateChange($event)" [ngModelOptions]="{updateOn: 'change'}" 
       #dateStart="ngModel" myDateValidator 
       [dateStart]="contract.startDate" [dateEnd]="contract.endDate" 
       class="datepicker-input datepicker-border"
       style="width:100%" bsDatepicker required>

mycomponent.component.ts

onStartDateChange(event) {
  if(event) {
    this.contract.startDate = event;
  }
}

my-date-validator.directive.ts

import { Directive, Input } from '@angular/core';
import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';

@Directive({
  selector: '[myDateValidator]',
  providers: [{provide: NG_VALIDATORS, useExisting: DateValidator, multi: true}]
})
export class DateValidator implements Validator {
  @Input() dateStart: Date;
  @Input() dateEnd: Date;
  constructor() { }

  validate(c: AbstractControl): { [key: string]: any } | null {
    if (!c || !(c.value)) {
      return null;
    }
    if (this.dateEnd < this.dateStart) {
      return {myDateValidator: false};
    }
    return null;
  }
}

似乎事件处理程序onStartDateChange()在验证发生之前被触发并且contract.startDate实际上已更新,验证器指令dateStart输入总是在验证过程中捕获旧值而不是新值被触发。关于相同问题的类似thread 已经存在。 欢迎任何帮助。

【问题讨论】:

    标签: angular typescript validation directive


    【解决方案1】:

    你可以尝试 (keyPress) 事件而不是 (ngModelChange)

    【讨论】:

    • 也没用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多