Angular utilizes the Renderer2
class to manipulate our view, acting as a protective shield between Angular and the DOM
, making it possible for us to modify elements without directly interacting with the DOM
ourselves.
ElementRef
provides another way to alter the view, but Angular advises against its use due to security concerns.. It is now commonly used in conjunction with renderer for efficient DOM
manipulation, as shown below.
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);
}
}
The reasoning behind using renderer as cited in this article is:
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 my application does not need to run in environments lacking DOM access, is there still a valid reason not to manipulate the DOM
directly within an Angular app?
If so, what are the specific reasons? (e.g. security/performance considerations)