角材料日期选择器格式区域设置

时间:2019-07-26 10:40:31

标签: javascript angular angular-material momentjs angular-formly

我创建了一个有角材料日期选择器组件以与formly一起使用,并尝试将其设置为对区域设置使用GB,以便日期显示为26/07/2019。但是,输入日期时,它仍解析为美国,从而导致显示无效的日期错误。

我尝试加入momentMomentDateAdapter模块,但无法解决问题。

这里是stackblitz

我将提供者设置为:

providers: [   
  { provide: LOCALE_ID, useValue: 'en-GB' },
  { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
  { provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS },
]

我的组件看起来像这样:

import { Component, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { FieldType } from '@ngx-formly/material';
import { MatInput } from '@angular/material';

import * as _moment from 'moment';
// tslint:disable-next-line:no-duplicate-imports
import {default as _rollupMoment} from 'moment';

const moment = _rollupMoment || _moment;

@Component({
  selector: 'app-form-datepicker-type',
  template: `
    <input matInput
      [errorStateMatcher]="errorStateMatcher"
      [formControl]="formControl"
      [matDatepicker]="picker"
      [matDatepickerFilter]="to.datepickerOptions.filter"
      [formlyAttributes]="field">
    <ng-template #matSuffix>
      <mat-datepicker-toggle [for]="picker"></mat-datepicker-toggle>
    </ng-template>
    <mat-datepicker #picker></mat-datepicker>
  `,
})
export class DatepickerTypeComponent extends FieldType {
  // Datepicker takes `Moment` objects instead of `Date` objects.
  date = new FormControl(moment([2017, 0, 1]));
}

2 个答案:

答案 0 :(得分:0)

Sam,“键”使用两个提供程序“ MAT_DATE_FORMAT”和DateAdapter来解析/格式化值

{
        "2019-7-25": {
            "num_count": 5
        },
        "2019-7-26": {
            "num_count": 5
        }
    }

如果用作DateAdapter MomentDateAdapter的提供,也要注入MAT_DATE_LOCALE

providers: [
    {provide: DateAdapter, useClass: CustomDateAdapter},
    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
  ],

请参阅official docs

但是您也可以使用CustomDateAdapter,它是一个具有两种功能的类,格式和解析

{provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]}

请参见example in stackblitz

答案 1 :(得分:0)

将LOCALE_ID更改为MAT_DATE_LOCALE