Multilingual web app in angular 4

  1. Install Via npm npm install @ngx-translate/core —save and nom install @ngx-translate/ http-loader —save
  2. Import HttpModule, Http, TranslateModule, TranslateLoader and TranslateHttpLoader in module.ts

import { TranslateHttpLoader } from’@ngx-translate/http-loader’;

import { HttpModule, Http } from’@angular/http’;

import { TranslateLoader, TranslateModule } from’@ngx-translate/core’;

exportfunctionHttpLoaderFactory(http: Http) {

returnnewTranslateHttpLoader(http);

}

@NgModule({

declarations: [

AppComponent,

],

imports: [

BrowserModule,

HttpModule,

TranslateModule.forRoot({

loader: {

provide:TranslateLoader,

useFactory:HttpLoaderFactory,

deps: [Http]

}

}),

],

providers: [MdDatepickerIntl],

bootstrap: [AppComponent]

})

3.Create a constructor and translation function in app.component.ts

import { TranslateService } from’@ngx-translate/core’;

import { Component } from’@angular/core’;

@Component({

selector:’app-root’,

templateUrl:’./app.component.html’,

styleUrls: [‘./app.component.css’]

})

exportclassAppComponent {

dir: string;

constructor(privatetranslate: TranslateService) {

translate.addLangs([‘en’, ‘ar’]);

translate.setDefaultLang(‘ar’);

translate.use(‘ar’);

}

changeLang(lang: string, direction: string ) {

this.dir = direction;

this.translate.use(lang);

}

}

5. add translate button in app.component.html

<buttonclass=”btn btn-sm btn-danger btn-srch pull-right” (click)=”changeLang(‘en’, ‘ltr’)”>En</button>

<buttonclass=”btn btn-sm btn-danger btn-srch pull-right” (click)=”changeLang(‘ar’, ‘rtl’)”>عربى</button>

6.create i18n folder inside assets and create ar.json for arabic language and en.json for english language

code in ar.json

{

“search”: “بحث”,

“search-for-hotel”: “البحثعنفندق”

}

code in en.json

{

“search”: “Search”,

“search-for-hotel”: “Search for Hotel”

}

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2016 InfoxIT Portal. All rights reserved.
Seo wordpress plugin by www.seowizard.org.
Scroll To Top
Visit Us On FacebookVisit Us On Google PlusVisit Us On YoutubeCheck Our Feed