Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Angular2 translation from component or service

I am currently in the process of translating my first Angular2 application based on the guidelines in https://angular.io/docs/ts/latest/cookbook/i18n.html

The examples only always show how to apply the i18n attribute to template code and how the template's code is then internationalized.

How would I access localized text from the component's code (the .ts file) or inside a service? I need this for interaction with some JavaScript libraries I am using, where I need to call a JavaScript function with the localized text.

like image 788
Martin C. Avatar asked Nov 11 '16 13:11

Martin C.


2 Answers

If you were using ng2-translate module, you could just inject TranslateService:

constructor(private translateService: TranslateService) { }

and use its get(translationKey: string) method returning an Observable.

this.translateService.get('stringToTranslate').subscribe(
    translation => {
        console.log(translation);
    });
like image 175
Daniel Kucal Avatar answered Oct 13 '22 13:10

Daniel Kucal


I'm using the attribute translation feature.

import {Component, Input, OnInit} from '@angular/core';

@Component({
    selector: 'app-sandbox',
    templateUrl: 'sandbox.html'
})
export class SandboxComponent implements OnInit {
    @Input()
    public title: string;

    constructor() {
    }

    ngOnInit() {
        console.log('Translated title ', this.title);
    }
}

From the parent component template:

<app-sandbox i18n-title title="Sandbox"></app-sandbox>

It is a workaround, but still, I think it's the cleanest one so far. It gives you access to the translated title within ts.

like image 22
Lucianovici Avatar answered Oct 13 '22 13:10

Lucianovici