Angular Material 5 - 如何在mat-datepicker中自定义日期

Sah*_*rav 7 angular-material angular angular5

如何以MM/DD/YYYY格式自定义mat-datepicker日期?

我正在使用以下配置:

HTML:

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

TS:

import {Component} from '@angular/core';

/** @title Basic datepicker */
@Component({
  selector: 'datepicker-overview-example',
  templateUrl: 'datepicker-overview-example.html',
  styleUrls: ['datepicker-overview-example.css'],
})
export class DatepickerOverviewExample {}
Run Code Online (Sandbox Code Playgroud)

当我打印表单值时,它给出了以下输出:

2017年12月31日星期日00:00:00 GMT + 0530(IST)

我期待MM/DD/YYYY的格式.

我试过这个配置:https://material.angular.io/components/datepicker/overview#customizing-the-parse-and-display-formats

但它对我不起作用.我正在使用默认的MatNativeDateModule(不是时刻js)

Saj*_*ran 8

您可以使用Date Pipe,如下所示,

<input mdInput placeholder="Title" [ngModel]="mydate  | date:'MM-dd-yyyy'">
Run Code Online (Sandbox Code Playgroud)

DEMO

  • 作为附件信息.formControlName只作为静态参数存在,你不能`[formControlName] ="myDate | date:'MM-dd-yyyy'"`,你被迫做`[formControlName] ="myDate`,其中myDate是其中之一反应形式的构造成员,这意味着你必须在打字稿方面执行管道,我不知道如何做到这一点. (4认同)
  • 谢谢。当我添加 [ngMode]="mydate | date:'MM-dd-yyyy'" 它说。'FormDateComponent' 类型不存在属性 'mydate' 知道这里有什么问题吗? (2认同)
  • `ngModel` 已被弃用,我们被迫在 Angular 6+ 中使用 `formControlName`。这个问题需要一个新的答案或者这个答案需要更新。 (2认同)

Moh*_*ngh 6

以下代码将格式化您的角度应用程序中所有日期选择器的日期。

为日期格式创建一个常量。

export const DateFormat = {
 parse: {
 dateInput: 'input',
 },
display: {
dateInput: 'MM/DD/YYYY',
monthYearLabel: 'MMMM YYYY',
dateA11yLabel: 'MM/DD/YYYY',
monthYearA11yLabel: 'MMMM YYYY',
}
};
Run Code Online (Sandbox Code Playgroud)

并在应用模块中使用以下代码

providers: [
  { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
  { provide: MAT_DATE_FORMATS, useValue: DateFormat }
 ]
Run Code Online (Sandbox Code Playgroud)