【问题标题】:Angular Material DatePicker not Changing when Moment locale does当 Moment 语言环境更改时,Angular Material DatePicker 不会更改
【发布时间】:2019-01-02 21:44:52
【问题描述】:

详情:Angular Material 7 DatePicker with moment js

问题:当我的 Web 应用程序的语言更改时,日期选择器不会更改语言环境。

期望的结果:每次我更改应用程序中的语言时,我的日期选择器也应该更改为该区域设置格式和语言。目前,我需要在 dd/MM/yyyy 和 MM/dd/yyyy 之间切换。

谁能指出我正确的方向?我是新手,似乎无法正确完成格式化。

代码:

HTML

<mat-form-field>
  <mat-label>From date</mat-label>
  <input name="fromDate" [min]="minDate" [max]="maxDate" [formControl]="displayFromDate" 
                     matInput [matDatepicker]="fromDatePicker">
  <mat-datepicker-toggle matSuffix [for]="fromDatePicker"></mat-datepicker-toggle>
  <mat-datepicker #fromDatePicker disabled="false"></mat-datepicker>
</mat-form-field>

我的一些翻译服务代码改变了地区设置: lang 参数将是“en”或“fr”,并由应用程序正在侦听的开关切换。

public use(lang: string): void {
  this._currentLang = lang;
  moment.locale(lang);      
  this.currentLang$.next(this.currentLang);
}

App.module.ts

import { MAT_MOMENT_DATE_FORMATS, MomentDateAdapter } from '@angular/material-moment-adapter';

import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';

import localeFr from '@angular/common/locales/fr';
import localeEn from '@angular/common/locales/en';

registerLocaleData(localeFr);
registerLocaleData(localeEn);

...

imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,

...

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

使用日期选择器的组件代码:

this.translationService.currentLang$.subscribe(currentLang => {      
  this.displayFromDate = new FormControl({ value: moment(this.displayFromDate.value).format(), disabled: true });
  console.log('displayFromDate', this.displayFromDate);
});

【问题讨论】:

    标签: angular typescript datepicker angular-material


    【解决方案1】:

    我在 Angular 文档中错过了这一点。如果其他人在挖掘相同的信息时遇到这种情况,请确保您使用数据适配器来设置您的语言环境。

    constructor(private adapter: DateAdapter<any>) {}
    
    toggleLocale() {
      this.adapter.setLocale(moment.locale());
    }
    

    【讨论】:

      【解决方案2】:

      You can call moment.tz.guess() with an optional boolean argument "ignoreCache". If set to true, the cache will be ignored and overwritten with the new value.

      Moment 文档 URL - https://momentjs.com/timezone/docs/#/using-timezones/guessing-user-timezone/

      工作示例 - https://codesandbox.io/s/material-date-locale-jyylz

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多