Search code examples
angulartranslate

Angular Translate implementation


Please suggest me an implementation for translation of angular app to different languages. I have used ngx-translate also. But wan to translate entire app at once?


Solution

  • You can use angular i18n translation technique

    i18n translation technique

    Create minimal Angular4 project We use @angular/cli to create a new project named “traduction” in the terminal:

     ng new traduction --prefix tr
        cd traduction
        ng serve -o
    

    Install and load ngx-translate

    Use npm in your terminal within the project folder “traduction”:

    npm install @ngx-translate/core --save
    npm install @ngx-translate/http-loader
    

    Import the necessary modules into app.module.ts :

    import { HttpClientModule, HttpClient } from '@angular/common/http';
    import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
    import { TranslateHttpLoader } from '@ngx-translate/http-loader';
    

    Add a function, that returns a “TranslateHttpLoader” and export it (needed by AoT). In this case the HttpLoaderFactory function we create, returns a Object that can load Translations using Http and .json, but you could write your own Class that for example uses a global JavaScript variable instead of loading a file, or that uses Google Translate:

    export function HttpLoaderFactory(http: HttpClient) {
      return new TranslateHttpLoader(http);
    }
    

    We then need to import our modules into the @NgModule, this is the import that tells Angular to load this Module into your AppModule:

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        HttpClientModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
            deps: [HttpClient]
          }
        })
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    

    It would have been so much easier if Angular would have used the keywords “load” or “submodule” instead of “import”, cause at the beginning it’s easy to confuse the ES2015 import with the NgModule import.

    Inject the TranslateService

    In “app.component.ts” we now init the “TranslateService”, we import the TranslateService:

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

    Then inside the AppComponent Class we inject the service and define our default language. And to be ready for the next step, we add a function to switch the language.

    constructor(private translate: TranslateService) {
        translate.setDefaultLang('en');
      }
    
      switchLanguage(language: string) {
        this.translate.use(language);
      }
    

    Create .json translation files

    We now create our translation files inside the assets/i18n folder:

    src/assets/i18n/en.json

    {
        "Title": "Translation example",
        "Intro": "Hello I am Arthur, I am 42 years old."
    }
    

    src/assets/i18n/fr.json

    {
        "Title": "Exemple de traduction",
        "Intro": "Bonjour je m'appelle Arthur, j'ai 42 ans."
    }
    

    These are simple .json files that will be loaded by our “TranslateHttpLoader” we created in “app.module.ts”.

    Translate simple title and intro

    In app.component.html we add a header with the translate “directive” inside the “h1” tag. This directive will take the text inside the tag and replace it with the matching translation. If you use the directive you have to make sure, that there is nothing else inside the tag but the text.

    As a second example we use the “TranslationPipe” to translate a label with define as a inline string. As we sometimes have value inside a translation that we want to replace, we can pass a data object into the “translate” pipe.

    <h1 translate>Title</h1>
    
    <div>
      {{ 'Intro' | translate:user }}
    </div>
    

    Integrate language switcher

    We can now attach our language switcher function that we saw above in app.component.ts to a button. In this case we create a button for each language and call the switchLanguage() function with the matching language key.

    <button (click)="switchLanguage('en')">en</button>
    
    <button (click)="switchLanguage('fr')">fr</button>
    

    Translate sentence with variable

    As mentioned before, you sometimes have sentences to that contain variable. In this little example we have a user object with age and name inside the “app.component.ts”, and we want to translate a sentence that will contain this values:

    ...
    export class AppComponent {
      user = {
        name: 'Arthur',
        age: 42
      };
    ...
    }
    

    Because we pass this object into the “translate” pipe, we can now use it’s properties in our translation with the {{ placeholder }} notation.

    src/assets/i18n/en.json

    {
        "Title": "Translation example",
        "Intro": "Hello I am {{name}}, I am {{age}} years old."
    }
    

    src/assets/i18n/fr.json

    {
        "Title": "Exemple de traduction",
        "Intro": "Bonjour je m'appelle {{name}}, j'ai {{age}} ans."
    }
    

    Using nested .json objects

    If you want to be able to have more control on your translation, and for example translate page blocks (from the end-user perspective) or components (from the developer perspective), one solution could be the following; use nested .json objects as described in the git repo. An example could look like this in the -json files:

    {
        "Title": "Translation example",
        "Intro": "Hello I am {{name}}, I am {{age}} years old.",
        "Startpage": {
            "TranslationSections": "Hello World"
        },
         "Aboutpage": {
            "TranslationSections": "We are letsboot"
        }
    }
    
    {
        "Title": "Exemple de traduction",
        "Intro": "Bonjour je m'appelle {{name}}, j'ai {{age}} ans.",
        "Startpage": {
            "TranslationSections": "Bonjour Monde"
        },
        "Aboutpage": {
            "TranslationSections": "Nous sommes letsboot"
        }
    }
    

    And in the corresponding template:

    <h1 translate>Title</h1>
    
    <div>
      {{ 'Intro' | translate:user }}
    </div>
    
    <div>
      {{ 'Startpage.TranslationSections' | translate }}
    </div>
    
    <div>
      {{ 'Aboutpage.TranslationSections' | translate }}
    </div>
    
    <br/>
    
    <button (click)="switchLanguage('en')">en</button>
    <button (click)="switchLanguage('fr')">fr</button>
    

    Example: angular translation