Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 - add style to specific element dynamically

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.

like image 731
Karan Avatar asked Jun 18 '18 11:06

Karan


People also ask

How do I add dynamic CSS in angular 6?

create a new component and create a service to load dynamic css variables from API. Add style tag in template file and use variable values for properties. Load this template on all pages or on main template. On app build style will be moved to head tag.


1 Answers

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;  } 
like image 185
Chris Stanley Avatar answered Nov 05 '22 11:11

Chris Stanley