簡體   English   中英

angular 8 中的國際化翻譯整個應用程序

[英]Internationalization in angular 8 to translate whole application

我想用選定的語言翻譯我的整個應用程序。 我有一個使用 i18n 進行翻譯的示例。 但我不明白如何在我的應用程序中實現它。

您只需按照我的一些說明進行操作即可更好地理解。

  1. 在您的應用程序中安裝 ngx-translate npm package。
npm i @ngx-translate/core --save
  1. 現在你需要安裝 http-loader
npm install @ngx-translate/http-loader --save
  1. 現在將此代碼粘貼到您的 AppModule.ts 文件中
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
          useFactory: myHttpLoader, 
          deps: [HttpClient]
      }
    })
  ],
  bootstrap: [AppComponent]
})

export function myHttpLoader(http: HttpClient) {
    return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
  1. 在 /assets/i18n/ 文件夾中創建語言(如印地語、英語等)的翻譯文件。
  //1. first file name: en.json
  { 
    "Title":"Welcome"
  }

  //2. second file name: hi.json
  {
    "Title":"स्वागत हे"
  }

//Note: you can use google translate to convert into any language.

  1. 在組件 ts 文件中導入翻譯服務。
import {TranslateService} from '@ngx-translate/core';

export class AppComponent {
  constructor(translate: TranslateService) {
    translate.addLangs(['en', 'hi'])
    translate.setDefaultLang('en');
    translate.use('en');
  }

  //if user on change language
  switchLanguage(language: string) {
    this.translate.use(language);
  }
}
  1. 在 html 文件中
  <p translate>Title</p>

  <button (click)="switchLanguage('en')">English</button>

  <button (click)="switchLanguage('hi')">Hindi</button>

繼續編碼。 請享用!

我希望它對你有幫助。 :)

在 Angular 版本 8 中,我建議您使用ngx-translate package。 它具有比 Angular 8 更多的功能,並且實現起來非常簡單。 據我所知,它是由一名團隊成員開發的,以彌補 i18 的局限性。

npm install @ngx-translate/core --save

它很容易安裝: https://github.com/ngx-translate/core/blob/master/README.md#installation

它依賴.json文件作為鍵值對來存儲/訪問翻譯后的值。

如果您打算升級到版本 9 及更高版本,您應該查看官方文檔,因為現在它已經改進了很多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM