Adding a translation service to an Angular application

 1. Under assets - create i18n folder and put there the translation files with the {lang}.json pattern.
A translation file should hold the values in this form:
{
    "Back": "Back"
}

or

{
    "Button":
     {
            "Back": "Back"
     }
}

2. Install @ngx-translate by running:

npm install @ngx-translate/core --save

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

3. Import the translate module in a shared module that also exports it. 

export function HttpLoaderFactory(http: HttpClient) {
    return new TranslateHttpLoader(http, './assets/i18n/');
}

imports: [TranslateModule.forRoot({
    loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient],

    },
    defaultLanguage: "en"
})],
exports: [TranslateModule]

4. Import the shared module in other modules.

5. Use with a pipe 

{{'BACK' | translate }}


Post a Comment

Previous Post Next Post