Styling with ElementRef and Renderer2
Styling with ElementRef and Renderer2
This is the documentation for Angular 7.
You can switch to the latest version Angular 8.
You can switch to the latest version Angular 8.
If we want to access the DOM element directly to manipulate its styles. In order to do that we need to inject ElementRef
and access to the nativeElement
property. This will give us access to the DOM APIs.
export class DemoComponent {
constructor(private element: ElementRef){
let el = this.element.nativeElement;
// Option 1
el.style.color = 'white';
el.style.background = 'red';
// Option 2
el.style.cssText = 'color: white; background: red;";
// Option 3
el.setAttribute('style', 'color: white; background: red');
}
}
Renderer2
The Renderer2
class is a service that provides an abstraction for UI rendering manipulations. Using it is the recommended approach because it then makes it easier to develop apps that can be rendered in different environments.
export class DemoComponent {
constructor(
private element: ElementRef,
private renderer: Renderer2,
){
let el = this.element.nativeElement;
renderer.setElementStyle(el, 'color', 'white');
renderer.setElementStyle(el, 'background', 'red');
}
}