You can use Renderer2 to set style as well, The prototype of setStyle is as following:
setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2): void
Parameters:
el: any, The element for whcih you set the style.
style: string, The name of the style.
value: any, The new value for style.
flags RendererStyleFlags2, Flags for style variations. No flags are set by default.
So you have to avoid use of ElementRef because direct access to the dom is not good for security, it is not safe, You can instead use Renderer2 to set Style
Demo example:
https://stackblitz.com/edit/renderer2-example-2-oryw2m?file=src/app/app.component.ts
Code 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');
}
}