Angular Material Date Validator 获取无效值

标签 angular forms input datepicker angular-material

<mat-form-field>
<input matInput [(ngModel)]="myDate" name="myDate" [matDatepicker]="Datepicker"
                        (click)="Datepicker.open()" >
<mat-datepicker-toggle matSuffix [for]="Datepicker"></mat-datepicker-toggle>
<mat-error>Invaild Date</mat-error>
</mat-form-field>
<mat-datepicker #Datepicker></mat-datepicker>

this.form = this.fb.group({
      myDate: [this.dateService.dateValidator]
});


dateValidator(control: FormControl) {
      console.log(control.value) <<<< problem here
}

亲爱的,

我试图在日期字段中输入日期值“1”,但是 dateValidator 中的 control.value 返回 2001-01-01 GMT 00:00。它使 dateValidator 始终通过,即使我在日期字段中填写了“1”。如何从“control.value”中获取原始值“1”而不是自动转换的值?谢谢

最佳答案

之所以会出现这种情况是因为 Material registers an input listener在其 DatePicker 的输入上:

_onInput(value: string) {
  let date = this._dateAdapter.parse(value, this._dateFormats.parse.dateInput);

parse() 方法does this :

parse(value: any): Date | null {
  if (typeof value == 'number') {
    return new Date(value);
  }

因此,当用户在您的输入中写入 1 时,在后台它变成了 new Date(1)

所以要回答您的问题 - “我如何从“control.value”中获取原始值“1”,您可以同时覆盖 input更改事件:

<input matInput 
       [(ngModel)]="myDate" 
       name="myDate" [matDatepicker]="Datepicker"
       (click)="Datepicker.open()" 
       (input)="someMethod($event.target.value)" 
       (change)="someMethod($event.target.value)">

关于Angular Material Date Validator 获取无效值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51633047/

相关文章:

angular - mongodb中看不到数据

java - java中只接受唯一的输入

html - 谷歌浏览器 v.30 : CSS overflow attribute on input elements cause other inputs to jump on focus state

angular - 如何禁用 TurboTable 组件上取消选择行的选项?

angular - 如何以正确的方式使用 Angular2 CLI 安装 postcss

javascript - 使用过滤器或管道将产品类别加载到 Ionic 2 的页面中?

jQuery hide() 不隐藏父级

html - 表单不会缩小到我的 iPhone 屏幕的宽度

php - 表单内的表单 HTML

javascript - Alert On input Field 在表单中点击 3 次