- Inject
ElementRef
andRenderer2
into your component: These services are provided by Angular to manipulate elements in a way that respects Angular’s view encapsulation and change detection mechanisms. - Use
Renderer2
to add a class: You can utilizeRenderer2
to add a class without directly touching the DOM element, maintaining abstraction and testability.
Here’s an example:
import { Component, ElementRef, Renderer2, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `
<div id="uniqueId">This is a unique element</div>
`
})
export class MyComponent implements AfterViewInit {
constructor(private el: ElementRef, private renderer: Renderer2) {}
ngAfterViewInit() {
// Find the element by ID using nativeElement querySelector
const element = this.el.nativeElement.querySelector('#uniqueId');
// Check if the element exists and add a class using Renderer2
if (element) {
this.renderer.addClass(element, 'new-class');
}
}
}