如何为datepicker实现MD_DATE_FORMATS?

cha*_*_pl 8 angular-material angular

我正在尝试从material2为闪亮的新datepicker实现我自己的日期格式.根据文档,我必须提供我的MD_DATE_FORMATS版本:

providers: [
  {provide: DateAdapter, useValue: NativeDateAdapter },
  {provide: MD_DATE_FORMATS, useValue: MY_DATE_FORMATS },
],
Run Code Online (Sandbox Code Playgroud)

当我使用默认实现时:

export const MD_NATIVE_DATE_FORMATS: MdDateFormats = {
  parse: {
    dateInput: null,
  },
  display: {
    dateInput: {year: 'numeric', month: 'numeric', day: 'numeric'},
    monthYearLabel: {year: 'numeric', month: 'short'},
    dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
    monthYearA11yLabel: {year: 'numeric', month: 'long'},
  }
};
Run Code Online (Sandbox Code Playgroud)

我收到日期输入为空的错误.但它到底是什么类型的?文档说任何.

如果我尝试放一些虚拟函数,我会得到错误: _dateAdapter.parse is not a function.

function dateInput() {
    return 'ddd';
}
const MY_DATE_FORMATS: MdDateFormats = Object.assign({}, MD_NATIVE_DATE_FORMATS, {parse: dateInput });
Run Code Online (Sandbox Code Playgroud)

如何使它工作?

Pet*_*erS 5

非常感谢推动解决方案的@MariusR.如上所述,您需要提供自己的日期适配器.从plunkr,这很简单如下:

export class OurDateAdapter extends NativeDateAdapter {
  parse(value: any): Date | null {
    if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
      const str = value.split('/');
      return new Date(Number(str[2]), Number(str[1])-1, Number(str[0]), 12);
    }
    const timestamp = typeof value === 'number' ? value : Date.parse(value);
    return isNaN(timestamp) ? null : new Date(timestamp);
  }
}
Run Code Online (Sandbox Code Playgroud)

这可以是您的任何TS文件,只需要在组件的模块中使用日期选择器提供:

  providers: [
    {provide: DateAdapter, useClass: OurDateAdapter}
  ]
Run Code Online (Sandbox Code Playgroud)

在组件中,您需要在构造函数中使用它:

  constructor(private dateAdapter: DateAdapter<Date>) {
    this.dateAdapter.setLocale('en-GB');
  }
Run Code Online (Sandbox Code Playgroud)

可以在这里收集语言环境列表,plunkr示例使用葡萄牙语,我的是英国英语.

http://www.i18nguy.com/unicode/language-identifiers.html

MariusR,鞠躬,为什么官方文档不能有这个?


Mar*_*usR 1

在你的代码中你应该替换

{provide: DateAdapter, useValue: NativeDateAdapter },
Run Code Online (Sandbox Code Playgroud)

{provide: DateAdapter, useClass: NativeDateAdapter },
Run Code Online (Sandbox Code Playgroud)

因为 NativeDateAdapter 是一个类而不是常量。

这应该可以解决 .parse is not a function 错误的问题。

但我无法复制日期输入为空错误。可能是由于相同的 useClass 问题,但如果您仍然遇到错误,您可以像这样定义 dateInput

parse: {
  dateInput: {year: 'numeric', month: 'numeric', day: 'numeric'},
},
Run Code Online (Sandbox Code Playgroud)

或一个变体

parse: {
  dateInput: 'YYYY-MM-DD',
},
Run Code Online (Sandbox Code Playgroud)

  • 您可能需要构建自己的自定义适配器。例如,这里如何提到https://github.com/angular/material2/issues/4955#issuecomment-306008040,并且可以在问题中提到的plunkr中找到一个示例(https://plnkr.co/edit/FlgGpjqyDlypas0VZJzo? p=预览) (3认同)