Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renderer2 Angular necessary?

I know that Angular uses Renderer2 class for manipulation our view. It serves as an abstraction layer between provided by angular to allow us manipulate elements of our application without having to touch the DOM directly ourselves.

ElementRef also is way to manipulate the view but Angular advices us not to use this because of security reasons. Now it is being using in conjunction with renderer to manipulate the DOM like this.

import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({ 
     selector: '[Randomdirective]' 
})
export class Randomdirective{
   constructor(private elRef: ElementRef, private renderer: Renderer2) {
   }
   @HostListener('click') 
   performTask() {
     const li = this.renderer.createElement('li');
     const text = this.renderer.createText('Click here to add li');
     this.renderer.appendChild(li, text);
     this.renderer.appendChild(this.elRef.nativeElement, li);
   }
}

I saw from this source that renderer is used because:

this approach makes it easier to develop apps that can be rendered in environments that don’t have DOM access, like on the server, in a web worker or on native mobile.

If I'm not planning on have my app run in environments that have don't DOM access, would it still be a 'bad practice' to directly manipulate the DOM in Angular app?

If so why? (e.g. security/performance reasons?)

like image 939
Willem van der Veen Avatar asked Jan 31 '26 04:01

Willem van der Veen


1 Answers

If you aren't going to ssr, it's only bad practice to touch the dom because it's not the angular way, there are way better and more performant ways than appendchild, like *ngFor.. though yes angular does also some sanitation etc.

like image 78
funkizer Avatar answered Feb 02 '26 16:02

funkizer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!