Angular 5 - add style to specific element dynamically Angular 5 - add style to specific element dynamically angular angular

Angular 5 - add style to specific element dynamically


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; }


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 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