If you want to apply styles, you can utilize the Renderer2 method. The setStyle prototype is structured as shown below:
setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2): void
Parameters:
el: any, Refers to the element where the style will be applied.
style: string, Indicates the name of the style.
value: any, Represents the new value for the style.
flags RendererStyleFlags2, Optional flags for different style variations. By default, no flags are set.
It is recommended to avoid using ElementRef due to security concerns related to direct DOM access. Instead, prefer using Renderer2 to set styles.
For a demonstration example, check out:
https://stackblitz.com/edit/renderer2-example-2-oryw2m?file=src/app/app.component.ts
Here's a code snippet as an example:
import { Component, Renderer2, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
@ViewChild('test') test: ElementRef;
constructor(private renderer: Renderer2) {}
ngAfterViewInit() {
this.renderer.setStyle(this.test.nativeElement, 'backgroundColor', 'red');
this.renderer.setStyle(this.test.nativeElement, 'color', 'white');
}
}