Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Multilingual Support

We are using Angular 2.0 in our Application. In that application we want to give multilingual support.We know using angular 1.0 how to implement. but don't know how to use in 2.0.

like image 279
Popat Shirsath Avatar asked Feb 18 '16 11:02

Popat Shirsath


1 Answers

I can recommend ngx-translate library, it's very easy to integrate and use.

1. Install via npm

npm install @ngx-translate/core --save

2. Add TranslateModule in app.module.ts imports

import {TranslateModule} from '@ngx-translate/core';

@NgModule({
   declarations: [...],
   imports     : [TranslateModule.forRoot(), ...],
   exports      : [...],
   providers   : [...],
   bootstrap   : [AppComponent]
})

export class AppModule {}

3. app.components.ts

import {Component} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';

@Component({
  selector   : 'app',
  templateUrl: './app.component.html',
})
export class AppComponent {
  constructor(private translate: TranslateService) {
    translate.addLangs(['en', 'hy']);
    translate.setDefaultLang('en');
    translate.use('en');
  }
  changeLang(lang: string) {
    this.translate.use(lang);
  }
}

4. app.component.html

<nav>
  <a [routerLink]="['/']">    
    {{ "home" | translate }}
  </a>
  |
  <a [routerLink]="['/about']">
    {{ "about" | translate }}
  </a>
  |
  <a [routerLink]="['/contact']">
    {{ "contact" | translate }}
  </a>
</nav>
<div class="lang-bar">
  <a (click)="changeLang('en')">EN</a>
  <a (click)="changeLang('hy')">ՀՅ</a>
</div>

5. Create i18n folder with translation files

en.json

{
    "home" : "Home",
    "about" : "About",
    "contact" : "Contact"
}

hy.json

{
    "home" : "Գլխավոր",
    "about" : "Մեր մասին",
    "contact" : "Հետադարձ կապ"
}
like image 84
styopdev Avatar answered Nov 10 '22 19:11

styopdev