简体   繁体   中英

Angular: How to enable multilingual support in Angular4

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.

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 !

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

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