I'm using Angular 5.2.9.
I was wondering when should I use Renderer2 over ngStyle ? Which is the best solution ?
1:<div #div>FOO BAR</div>
@ViewChild('div') div: ElementRef;
constructor(private renderer: Renderer2) {}
ngAfterViewInit() {
this.renderer.setStyle(this.div.nativeElement, 'background', 'blue');
}
2:<div [ngStyle]="styleValue">FOO BAR</div>
styleValue: any = {};
ngAfterViewInit() {
this.styleValue = {background: 'blue'};
}
I know that it is easier to use "ngStyle" in a ngFor, eg:
<div ngFor="let elem of array" [ngStyle]="styleValue">
Otherwise you should do for this case: <div ngFor="let elem of array" #div>FOO BAR</div>
@ViewChildren('div') divs: QueryList<ElementRef>;
constructor(private renderer: Renderer2) {}
ngAfterViewInit() {
this.divs.change.subscribe(() => {
this.toFlipArray.forEach((div) => {
this.renderer.setStyle(this.div.nativeElement, 'background', 'blue');
})
}
}
This seems much more longer in a ngFor to use Renderer2 and I have even not killed the subscription.
Is there a difference in performance ? Maybe somewhere else ?