在Angular 2中动态更改DatePipe的语言环境 [英] Dynamically change locale for DatePipe in Angular 2

查看:252
本文介绍了在Angular 2中动态更改DatePipe的语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个Angular项目,用户可以在该项目中切换语言.可以使语言环境动态化吗?

I'm making an Angular project where the user has the ability to switch languages. Is it possible to make the locale dynamic?

我已经看到您可以将其添加到NgModule中,但是我猜想当它放在其中时它不是动态的吗?还是我可以通过服务或其他方式对其进行更改?

I have seen that you can add it in the NgModule but i'm guessing it's not dynamic when i put it there? Or can i change it somehow through a service or something?

推荐答案

使用providers,您可以在NgModule中更改默认语言环境. 为此,您需要从angular/core导入LOCALE_ID并获取您的语言环境语言,以将其传递给提供程序.

Using providers you can change your default locale in your NgModule. to do this You need to import LOCALE_ID from angular/core and fetch your locale language to pass the same to providers.

import { LOCALE_ID } from '@angular/core';

@NgModule({
    imports: [//your imports],
    providers: [
        { provide: LOCALE_ID, useValue: "en-US" }
    ]
})

...
...
{
  provide: LOCALE_ID,
  deps: [SettingsService],      //some service handling global settings
  useFactory: (settingsService) => settingsService.getLanguage()  //returns locale string
}

希望这会对您有所帮助.

Hope this will help you.

这篇关于在Angular 2中动态更改DatePipe的语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆