Date pipe is Working fine in Html Interpolation but not Working in Mat-DatePicker Input Fields

烂漫一生 提交于 2021-02-10 23:13:42

问题


I want to display a date in dd/MM/YYYY format when a user pick the date using the mat Datepicker but when i use the Datepipe in Datepicker it not shows any Date when we pick

   <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:


Make sure you have imported DatePipe in your .ts

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

constructor(private date: DatePipe)

Note: If you have an error of static injection Datepipe then please import DatePipe in your module.ts file

If this is not fixing your issue then you can make function on date selection that transform your date to your preferred format just like below:

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

Now in your .ts file:

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

export class XComponent{

    constructor(private date: DatePipe)

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

}

Here are the available angular date pipe formats: https://angular.io/api/common/DatePipe



来源:https://stackoverflow.com/questions/53928624/date-pipe-is-working-fine-in-html-interpolation-but-not-working-in-mat-datepicke

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!