Angular 5 - add style to specific element dynamically

I came across a page that has good explanation and sample code to add the style dynamically in Angular 2+. Attach the style dynamically in Angular


As per our comments, You should be using document.querySelector after a life cycle hook

ngAfterViewInit() {
    (document.querySelector('.app-alerts') as HTMLElement).style.top = '150px';
}

I'm super late to this party, but NO! DO NOT USE DOCUMENT.QUERYSELECTOR. That is NOT how you style an Angular DOM element!

<div [ngStyle]="{'top.px': divStyle}">

Then in your component, you have

ngAfterViewInit() {
  this.divStyle = 200; 
}