Reputation: 36630
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?)
Upvotes: 3
Views: 1125
Reputation: 4897
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.
Upvotes: 3