日期管道在HTML插值中工作正常,但在Mat-DatePicker输入字段中不工作

时间:2018-12-26 07:08:42

标签: angular5 angular6 angular7

当用户使用垫子Datepicker选择日期时,我想以dd / MM / YYYY格式显示日期,但是当我在Datepicker中使用Datepipe时,我们选择时不显示任何日期

   <mat-form-field class="box">
    <input matInput [matDatepicker]="picker" placeholder="Generate Date" maxlength="10px" [readonly]="isNew1"
      [ngModel]="quotation?.generateDate | date: 'dd/MM/yy'"
      (ngModelChange)="quotation.generateDate=$event" [ngModelOptions]="{standalone: true}">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker [disabled]="isNew1" #picker></mat-datepicker>
  </mat-form-field>

1 个答案:

答案 0 :(得分:0)

确保已在.ts中导入DatePipe

import { DatePipe } from '@angular/common';

constructor(private date: DatePipe)

如果这不能解决问题,则可以对日期进行选择,将日期转换为您喜欢的格式,如下所示:

<mat-form-field class="box">
   <input matInput [matDatepicker]="picker" 
      placeholder="Generate Date"
      maxlength="10px"
      [readonly]="isNew1"
      [ngModel]="quotation?.generateDate"
      (ngModelChange)="onDateSelection(quotation?.generateDate)"
      [ngModelOptions]="{standalone: true}"
   >
   <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
   <mat-datepicker [disabled]="isNew1" #picker></mat-datepicker>
</mat-form-field>

现在在您的.ts文件中:

import { DatePipe } from '@angular/common';

export class XComponent{

    constructor(private date: DatePipe)

    onDateSelection(date: Date): string {
        return this.date.transform(date, 'yyyy-MM-dd');
    }

}