简体   繁体   中英

Internationalization in angular 8 to translate whole application

I want to translate my whole application with selected language. I got a example which is using i18n to translate. but i am not understand that how to implement it in my application.

You just follow my few instructions for better understanding.

  1. install ngx-translate npm package in your application.
npm i @ngx-translate/core --save
  1. now you need to install http-loader
npm install @ngx-translate/http-loader --save
  1. Now pate this code into your AppModule.ts file
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. Create translation files for languages (like hindi, english etc.) in your /assets/i18n/ folder.
  //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. Import translate service in your component ts file.
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. in html file
  <p translate>Title</p>

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

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

keep coding. enjoy!

I hope it is helpful for you. :)

In Angular version 8, I recommend you to use the ngx-translate package. It comes with much more features than Angular's version 8 an is pretty simple to implement. As far as I remember it was developed by one of the team member to compensate the limitations of the i18.

npm install @ngx-translate/core --save

It's pretty easy to install: https://github.com/ngx-translate/core/blob/master/README.md#installation

It relies on .json files as key values pair to store/access the translated values.

If you plan to upgrade to the version 9 and above you should take a look at the official documentation since now it has improved quite a lot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM