i have written the following directive because apparently ng2-translate is missing one:
import { Directive, ElementRef, Renderer, OnDestroy } from '@angular/core';
import { TranslateService } from 'ng2-translate';
import { Subscription } from 'rxjs';
@Directive({selector: '[translate]'})
export class TranslateDirective implements OnDestroy {
subscription: Subscription;
constructor(el: ElementRef, renderer: Renderer, translateService: TranslateService) {
let translateKey = el.nativeElement.attributes.translate.value;
this.subscription = translateService.get(translateKey).subscribe(value => {
el.nativeElement.innerHTML = value; // this works
// renderer.setText(el.nativeElement, value); // this doesn't work for some reason?
});
}
ngOnDestroy(): void {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}
As you can see I got it working using the low level "el.nativeElement.innerHTML" but it the API seems to imply that the "renderer.setText" call should work too. Instead it has no effect at all.
Question: why is that? What is the setText call supposed to do? Bonus: are there problems with the code or is there a good reason ng2-translate does not include one? bad idea?
Renderer.setTextwas never meant to be used for elements, only for text nodes.
And more from that comment:
To do this, just use
elementRef.nativeElement.textContent = ...directly.
This seems to be a breaking change in @angular 2.2.0. I've just encountered the same issue after upgrading from 2.1.0. The Renderer class is listed as experimental so I guess we can expect some instability :( https://angular.io/docs/js/latest/api/core/index/Renderer-class.html
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