我需要帮助.我不知道如何更改material 2日期提货器的日期格式.我已经阅读了文档,但是我不知道我实际上需要做什么.Datepicker默认提供的输出日期格式为F.E.:6/9/2017

我试图实现的是将格式更改为2017年6月9日或任何其他日期.

文档https://material.angular.io/components/component/datepicker对我一点帮助都没有.

推荐答案

以下是我找到的唯一解决方案:

首先,创建常量:

const MY_DATE_FORMATS = {
   parse: {
       dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
   },
   display: {
       // dateInput: { month: 'short', year: 'numeric', day: 'numeric' },
       dateInput: 'input',
       monthYearLabel: {year: 'numeric', month: 'short'},
       dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
       monthYearA11yLabel: {year: 'numeric', month: 'long'},
   }
};

然后,您必须扩展NativeDateADapter:

export class MyDateAdapter extends NativeDateAdapter {
   format(date: Date, displayFormat: Object): string {
       if (displayFormat == "input") {
           let day = date.getDate();
           let month = date.getMonth() + 1;
           let year = date.getFullYear();
           return this._to2digit(day) + '/' + this._to2digit(month) + '/' + year;
       } else {
           return date.toDateString();
       }
   }

   private _to2digit(n: number) {
       return ('00' + n).slice(-2);
   } 
}

In format function, you can choose whatever format you want

最后一步,您必须将其添加到模块提供程序中:

providers: [
    {provide: DateAdapter, useClass: MyDateAdapter},
    {provide: MD_DATE_FORMATS, useValue: MY_DATE_FORMATS},
],

就这样.我不敢相信没有简单的方法可以通过@Input更改日期格式,但我们希望它能在material 2(目前为beta 6)的future 版本中实现.

Angular相关问答推荐

如何在Angular应用程序部署中安全地管理环境变量

Angular中绑定嵌入标签src属性的问题

Angularmaterial 中的处理mat—radio—button表单值访问器

Angular 17自定义指令渲染不起作用'

带有服务依赖的Angular测试类

命令不起作用的初始菜单项

在Angular中使用ngFor进行表乘法

如何在Angular功能路由保护中取消订阅RxJs主题

从组件调用时服务中的 AddTodo 方法不起作用

执行ng generate environments时出错时需要合集和原理图

在 Angular material 表单元格中渲染 html

如何修复 [Object: null prototype] { title: 'product' }

如何将服务变量传递到 Angular Material 对话框?

如何在 Angular2 中的所有请求的请求标头中发送Cookie?

Angular 5 响应式表单 - 单选按钮组

如何从 EventEmitter 函数返回值?

错误:angular2 中没有 HttpHandler 的提供者

@HostBinding 与 Angular 中的变量类

如何在 Angular 应用程序中通过路由更改页面标题?

找不到@angular/common/http模块