Angular 2 - Multilingual Support

后端 未结 2 659
盖世英雄少女心
盖世英雄少女心 2021-02-01 10:19

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

2条回答
  •  天涯浪人
    2021-02-01 10:52

    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

    
    
    

    5. Create i18n folder with translation files

    en.json

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

    hy.json

    {
        "home" : "Գլխավոր",
        "about" : "Մեր մասին",
        "contact" : "Հետադարձ կապ"
    }
    

提交回复
热议问题