日期管道在HTML插值中工作正常,但在Mat-DatePicker输入字段中不工作 [英] Date pipe is Working fine in Html Interpolation but not Working in Mat-DatePicker Input Fields

查看:40
本文介绍了日期管道在HTML插值中工作正常,但在Mat-DatePicker输入字段中不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

推荐答案

确保已在.ts中导入了DatePipe

Make sure you have imported DatePipe in your .ts

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

constructor(private date: DatePipe)

注意:如果您遇到静态注入Datepipe错误,请在您的module.ts文件中导入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>

现在在您的.ts文件中:

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');
    }

}

以下是可用的日期日期管道格式: https://angular.io/api/common/DatePipe

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

这篇关于日期管道在HTML插值中工作正常,但在Mat-DatePicker输入字段中不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆