Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Renderer to do i18n?

I read recently very interesting article by @yearofmoo about Angular2 Renderer. It gave me an idea that it might be possible to do i18n with Renderer. Basically use this function:

  createText(parentElement: any, value: string): any {
    // this is called for every text node in the template
  }

and simply transform value by mapping it to different language:

let es = { "Hello": "Hola" }

value = "Hello"
value = es[value]

I looked briefly at the issues and design docs, but before going down this rabbit hole I wanted to check if anyone has any experience with this.

Are there any issues that could prevent this from working? Some breaking changes on the way I'm not aware of? Opinions about this approach?

like image 695
Sasxa Avatar asked Feb 24 '16 15:02

Sasxa


1 Answers

We use Renderer to set a translation that has been provided by a attribute.

import { Directive, ElementRef, Input, Renderer, OnInit} from '@angular/core';
import { TranslateService } from './translate.service';

@Directive({ selector: '[translate]' })
export class TranslateDirective  implements OnInit{

    @Input() translate :string;

   constructor(private el: ElementRef, private renderer: Renderer, private _translateService : TranslateService) {}

   ngOnInit(): void {
        this.renderer.setText(this.el.nativeElement,this._translateService.instant(this.translate));
   }
}

See plunker for demo

Hopefully this is what you where looking for.

like image 56
Maarten Mensink Avatar answered Sep 21 '22 18:09

Maarten Mensink