Search code examples
angularangular2-directivesng2-translate

ng2-translate directive: why does renderer.setText not work?


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?


Solution

  • Renderer.setText was 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.