Angular 4 i18n示例如何在角度4中实现i18n

时间:2017-09-16 17:35:23

标签: angular

如何在角度4中实现i18n。我在角度4中是新的。我想在角度4项目中实现i18n。该角度4项目由角度CLI生成。请帮帮我怎样才能做到。

提前致谢

2 个答案:

答案 0 :(得分:5)

这很简单。只是做:

npm install @ngx-translate/core @ngx-translate/http-loader --save

然后你应该在〜/ src / assets中创建一个名为i18n

的文件夹

导入app.module.ts模块

import {TranslateModule, TranslateLoader} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import {HttpClientModule, HttpClient} from '@angular/common/http';

在导入之前,您需要添加所有模块:

// AoT requires an exported function for factories
export function HttpLoaderFactory(http: HttpClient) {
    return new TranslateHttpLoader(http);
}

然后......在@NgModule IMPORTS

HttpClientModule,
    TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
            deps: [HttpClient]
          }
     })

并完成添加translateService

// ngx-translate
import { TranslateService } from '@ngx-translate/core';`

在构造函数中声明,然后设置默认语言

 constructor(public translate: TranslateService) {
    translate.addLangs(["en", "es"]);
        translate.setDefaultLang('en');

        let browserLang = translate.getBrowserLang();
        translate.use(browserLang.match(/en|es/) ? browserLang : 'en');
  }

完成此操作后,您需要创建文件:

〜/ src / assets / es.json和〜/ src / assets / en.json在我的情况下使用这种格式:

{
  "CARD": {
    "NAME": "Celiz Morante Matias Nahuel",
    "TITLE": "Full Stack JS Developer",
    "EMAIL": "mceliz@....it.com.ar",
    "PHONE": "+549....",
    "SKYPE": "enl...",
    "ADDRESS": "Jo.. Inge... ...40",
    "GITHUB": "https://github.com/G33N",
    "LINKEDIN": "https://www.linkedin.com/in/matias-nahuel-celiz-morante-994719149/"
  },
  "EXPERIENCE": {
    "TITLE": "Experience"
  },
  "EDUCATION": {
    "TITLE": "Education"
  },
  "PORTFOLIO": {
    "TITLE": "Portfolio"
  },
  "FOOTER": {

  }
}

这是调用模板的方式:

<h2>{{ 'EXPERIENCE.TITLE' | translate }}</h2>

这是https://github.com/ngx-translate/core#installation

的简历

答案 1 :(得分:2)

这可能是您正在寻找的: Angular 2+的国际化(i18n)库 https://github.com/ngx-translate/core