简体   繁体   中英

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.

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 .

  constructor(private translate: TranslateService) { }

  this.translate.get(this.pageTitle).subscribe((text:string) => {
      this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
        title.setTitle(this.translate.instant(text))
      });
    });        

if you want to detect on Language change use below code , pass your title key

this.setDocTitle('dashboard.title');

setDocTitle(titleKey: string) {
  this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
    this.translate.get(titleKey).subscribe((text:string) => {
    this.titleService.setTitle(this.translate.instant(text));
  });
  }); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM