Angular 5 - add style to specific element dynamically

Karan picture Karan · Jun 18, 2018 · Viewed 48.6k times · Source

I am using Angular 5.2 in my project and new to the angular framework. My component html is looking like this:-

enter image description here

I want to add the style="top:200px;" dynamically to the highlighted element with class="app-alerts" in the above screenshot in the angular ts code. The div element with class "app-alerts" get added to the DOM on the render.

Please suggest the code changes.

Answer

Chris Stanley picture Chris Stanley · Aug 14, 2018

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