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.
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);
});
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With