How to Use ngx-translate in Angular2 for internationalization, ngxtranslate
Compared with ng-translate in AngularJS, angular2 also has its own internationalized module, that is, ngx-translate.
Project address: https://github.com/ngx-translate/core
Use angular-cli to initialize the project:
ng new my-project
Use npm to install the ngx-translate Module
npm install --save @ngx-translate/core npm install --save @ngx-translate/http-loader
Introduce this module to the project's root module app. module. ts.
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';import { TranslateHttpLoader } from '@ngx-translate/http-loader';export function HttpLoaderFactory(http:Http){ return new TranslateHttpLoader(http, './assets/i18n/', '.json');}@NgModule({ declarations: [ AppComponent ], imports: [ ... TranslateModule.forRoot({ loader:{ provide:TranslateLoader, useFactory:HttpLoaderFactory, deps:[Http] } } ) ], providers: [], bootstrap: [AppComponent]})
Create an i18n folder under the assets folder and create a json file in two languages. (Such as zh-CN.json and en. json)
Json files are in the form of key-value. The key value represents the string to be translated. The value is the translation result of a specific language. Generally, the key value of a file without a language is the same, the value is different.
// Zh-CN.json {"welcome": "welcome to this application", "hello": "hello", "get-lang": "get language type"} // en. json {"welcome": "welcome to this app", "hello": "Hola "}
Then use the Translate service in the corresponding component.
Import {TranslateService} from '@ ngx-translate/core' @ Component ({...}) export class AppComponent {constructor (private translate: TranslateService) {// Add language support for translate. addLangs (['zh-cn', 'en']); // you can specify the default language. Generally, you can use translate when the language cannot be matched. setDefaultLang ('zh-cn'); // obtain the language of the current browser environment, such as en, zh let broswerLang = translate. getBrowserLang (); translate. use (broswerLang. match (/en | zh-CN /)? BroswerLang: 'zh-cn');} changeLang (lang) {console. log (lang); this. translate. use (lang);} toggleLang () {console. log (this. translate. getBrowserLang (); // obtain the language style, which is equivalent to a more detailed language type, such as zh-CN, zh-TW, and en-US console. log (this. translate. getBrowserCultureLang ());}}
Sample template:
<div>
This method is similar to ng-translate in angularjs, and uses the translate pipeline.
Effect:
Source Code address: https://github.com/justforuse/angular2-demo/tree/master/angular-translate
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.