简体   繁体   中英

How to add style to a class programmatically - Angular 2

In my application I am using a library which has not exposed its elements. I can only use it via it's selector.

I am overriding its css by using >>> . for example:

>>> .wrapper{ top: 0px !important; width: 400px !important; }

Now I want to add a new class temp-wrapper and in this class I want to add width: 100px !important .

I am able to add it by using classList.add('temp-wrapper') .

But problem is that width value is coming from another component when some event occurs. Is their any way by which I append some styles to a particular class in runtime.

Also I have used ngStyle and its not working as I have to use >>> in front of class name in order to override.

you can create a style element dynamically, put the css definations and add the component do document, eg:

var style = document.createElement('style');
style.id = "myStyleId" // so later you can track and update easily
var css = ".temp-wrapper { backdround-color: red; border: 1px solid blue; .......}";
style.innerHTML = css;
document.head.append(style);

In case you don't want to apply some inline style and want to add some class and want to create the class defination dynamicall

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM