Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 368
arturh Avatar asked Jun 09 '26 10:06

arturh


2 Answers

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.

like image 180
whatsthatitspat Avatar answered Jun 11 '26 07:06

whatsthatitspat


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

like image 20
Michael McGowan Avatar answered Jun 11 '26 05:06

Michael McGowan