溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

在Angular8.0下使用ngx-translate進行國際化配置的方法

發(fā)布時間:2021-02-03 13:38:21 來源:億速云 閱讀:286 作者:小新 欄目:web開發(fā)

小編給大家分享一下在Angular8.0下使用ngx-translate進行國際化配置的方法,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

一. 將ngx-translate添加到Angular應用程序中

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

二.在app.module.ts中初始化翻譯TranslateModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

// import ngx-translate and the http loader
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-translate and the loader module
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

// required for AOT compilation
export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(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']
})
export class AppComponent {
  constructor(private translate: TranslateService) {
    translate.setDefaultLang('en');
  }
}

四.在assets/i18n文件下創(chuàng)建讓我們?yōu)橛⑽姆g創(chuàng)建相關語言JSON文件,如en.json文件

{
 "demo.title": "Translation demo",
 "demo.text": "This is a simple demonstration app for ngx-translate"
}

五.在app.component.html中使用

<div>
  <!-- translation: translation pipe -->
  <h2>{{ 'demo.title' | translate }}</h2>

  <!-- translation: directive (key as attribute)-->
  <p [translate]="'demo.text'"></p>

  <!-- translation: directive (key as content of element) -->
  <p translate>demo.text</p>
</div>

看完了這篇文章,相信你對“在Angular8.0下使用ngx-translate進行國際化配置的方法”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI