如何在Angular8.0下使用ngx-translate进行国际化配置
一.将ngx-translate添加到Angular应用程序中
npminstall@ngx-translate/core@ngx-translate/http-loaderrxjs--save
二.在app.module.ts中初始化翻译TranslateModule
import{BrowserModule}from'@angular/platform-browser'; import{NgModule}from'@angular/core'; import{AppComponent}from'./app.component'; //importngx-translateandthehttploader import{TranslateLoader,TranslateModule}from'@ngx-translate/core'; import{TranslateHttpLoader}from'@ngx-translate/http-loader'; import{HttpClient,HttpClientModule}from'@angular/common/http'; @NgModule({ declarations:[ AppComponent ], imports:[ BrowserModule, //ngx-translateandtheloadermodule HttpClientModule, TranslateModule.forRoot({ loader:{ provide:TranslateLoader, useFactory:HttpLoaderFactory, deps:[HttpClient] } }) ], providers:[], bootstrap:[AppComponent] }) exportclassAppModule{} //requiredforAOTcompilation exportfunctionHttpLoaderFactory(http:HttpClient){ returnnewTranslateHttpLoader(http); }
三.在app.component.ts中设置初始值
import{Component}from'@angular/core'; import{TranslateService}from'@ngx-translate/core'; @Component({ selector:'app-root', templateUrl:'./app.component.html', styleUrls:['./app.component.scss'] }) exportclassAppComponent{ constructor(privatetranslate:TranslateService){ translate.setDefaultLang('en'); } }
四.在assets/i18n文件下创建让我们为英文翻译创建相关语言JSON文件,如en.json文件
{ "demo.title":"Translationdemo", "demo.text":"Thisisasimpledemonstrationappforngx-translate" }
五.在app.component.html中使用
{{'demo.title'|translate}}
demo.text
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。