0 day streak
javascript / intermediate
Snippet

Secure DOM Manipulation using Renderer2

Directly accessing the DOM via 'nativeElement' can be dangerous and breaks compatibility with non-browser platforms (like SSR). Renderer2 provides a safe abstraction layer to modify styles, attributes, and classes.

snippet.js
javascript
1
2
3
4
5
constructor(private renderer: Renderer2, private el: ElementRef) {}
highlight() {
this.renderer.addClass(this.el.nativeElement, 'active');
}
angular
Breakdown
1
private renderer: Renderer2
Injects the Angular renderer service for cross-platform safe DOM interactions.
2
this.renderer.addClass(...)
Safely applies a CSS class to an element without direct property manipulation.