【问题标题】:Change moment.js locale on the fly in Angular 8在 Angular 8 中即时更改 moment.js 语言环境
【发布时间】:2020-02-16 00:45:19
【问题描述】:

标题是我需要的。我的应用程序中有一个语言选择器下拉菜单,到目前为止,我一直在使用它来动态(不刷新页面)更改应用程序中的语言。当我尝试使用 moment.js'moment.locale(string) 执行此操作时,它不会像应用程序的其余部分那样更新视图。

setLocale(locale?: string) {
    if (!locale) locale = localStorage.getItem("locale") || "en-US";
    localStorage.setItem("locale", locale);
    this.adapter.setLocale(locale); //for date picker (nothing to do with moment.js)
    moment.locale(locale); // for moment.js ------------------- only works after refresh
    this.translate.use(locale); //rest of the app
}

这是从下拉列表中选择一种语言时调用的方法,但 moment.js 呈现的日期不会更新,而是直到页面刷新。

有没有办法做到这一点?黑客?解决方法?

谢谢

【问题讨论】:

标签: angular momentjs locale


【解决方案1】:

@Pipe({
  name: 'dynamicMoment'
})
export class MomentPipe implements PipeTransform {
  /**
   * MomentPipe constructor
   * @param {TranslateService} translate
   */
  constructor(private translate: TranslateService) {
  }

  /**
   * Make moment dynamic
   * @param {string} value
   * @param {string} format
   * @returns {any}
   */
  transform(value: string, format?: string): any {
    // make the moment format configurable
    format = format ? format : 'MMMM Do YYYY';
    // get the initial value
    const initVal = moment(value).locale(moment.locale()).format(format);
    // insert the value into a new behaviour subject. If the language changes, the behaviour subject will be 
    // updated
    const momentObs = new BehaviorSubject<string>(initVal);
    this.translate.onLangChange.subscribe(() => {
      // format the new date according to the new locale
      const val = moment(value).locale(moment.locale()).format(format);
      momentObs.next(val);
    });
    return momentObs; // needs to be piped into the async pipe
  }

}

【讨论】:

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