Angular 5: Dynamic CSS (for Component)

create dynamic css 3 rules for angular 5
dynamic css rules

Sometimes you need to generate some CSS during runtime applied to the entire site (instead of adding it to some specific elements). For example you might want to load some data from an API before you can generate the CSS.

With javascript (and Angular 5) this is easy to do. The same code can be applied to other Angular versions too.


First we create a new style sheet and add it to the header (for example in the constructor of a component).

let style = document.createElement("style");
this.styleSheet = style.sheet;

Deleting Rules

If you add Rules dynmically there might be an event on which u also want to change them. So it comes in handy, to be able to remove rules.
This example code will remove all rules from the stylesheet:

for (let i=0; i<this.styleSheet.rules.length; i++) {

Of course it is possible to scan for specific rules, by searching for its selector:

for (let i=0; i<this.styleSheet.rules.length; i++) {
  if (this.styleSheet.rules[i].selectorText === '#someID .someClass') {

removeRule will also work in older versions of the Internet Explorer. There is a newer variant called deleteRule which can be used if your are sure, that you don’t need to be compatible to old Internet Explorer versions.

Adding Rules

And of course we need a way of dynamically adding rules.

This can be achived with the following line:

this.styleSheet.insertRule("p {color: red;}");

Please feel free to ask your questions or post improvements in the comments!



Please enter your comment!
Please enter your name here