Reputation: 131
I have an application built with angularJs (version 4). i want to make this app available with two languages (French and English). I checked the official documentation but i'm confused and didn't get how to do it. can any one give the simple steps to translate my app ? thanks in advance.
Upvotes: 2
Views: 1103
Reputation: 396
ngx-translate package is good tool wich can help you achieve what you want. Here is how to do it step by step :
first install ngx-translate :
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader --save
define your languages files : create en.json file and the content should look like this :
{
"TEXT": "your text in english here! ", // add many as you need !
}
the same for your fr.json file with french translation
edit your app.module.ts:
import {TranslateModule, TranslateLoader} from "@ngx-translate/core";
import {TranslateHttpLoader} from "@ngx-translate/http-loader";
export function HttpLoaderFactory(httpClient: HttpClient) {
return new TranslateHttpLoader(httpClient, "i18n/", ".json");
}
in the @NgModule decorator imports add TranslateModule.forRoot()
use translate pipe:
Now you should be able to use the translate pipe in your template just like this :
{{ 'TEXT' | translate }}
now you need to authorize the user to change language. In order to do that you need to change the component :
add this import : import {TranslateService} from '@ngx-translate/core';
and change the constructor :
constructor( private translate: TranslateService) {
translate.addLangs(["en", "fr"]);
translate.setDefaultLang('en');
let browserLang = translate.getBrowserLang();
translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');
}
you add something like this in your html template, to allow the user to change the current langauge :
<select #langSelect (change)="translate.use(langSelect.value)">
<option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="lang === translate.currentLang">{{ lang }}</option>
</select>
Best of luck !
Upvotes: 3
Reputation: 1026
Ng translate will not support in angular2, you can use ngx-translate in angular2 and 4 web application. Find the sample configuration and working example in this plunker sample
command to install
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader --save
Upvotes: 2