Reputation: 13
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.
Upvotes: 1
Views: 1447
Reputation: 405
You just follow my few instructions for better understanding.
npm i @ngx-translate/core --save
npm install @ngx-translate/http-loader --save
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. 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.
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);
}
}
<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. :)
Upvotes: 2
Reputation: 15363
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.
Upvotes: 1