1

I'd like to add a class to one of my divs with a dynamic value generated in ts.

Say I have the following code to add a class:

let item = document.querySelector('.my-div');
item.classList.add('max-width');

let myMaxWidthValue = '200'; // this value is going to be generated by some fn

Now I would like to somehow make the class look like this in the css:

.max-width .innerItems {
  max-width: myMaxWidthValue
}

Is this possible? It would be way more efficient for me to do it this way.

As you can tell by my CSS I want to set the class to the parent that contains many children elements.

I could do getElementsByClassName and loop through each one with element[0].style.maxWidth = myMaxWidthValue but there could be a TON of these children elements and it does not seem right to do it this way.

halfer
  • 19,824
  • 17
  • 99
  • 186
cup_of
  • 6,397
  • 9
  • 47
  • 94
  • 1
    Check out this answer https://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript/524798#answer-524715 – felixmosh Sep 05 '19 at 17:04
  • 1
    Are you generating the html as well? Via ngFor, etc? If so, it may be better to add it as you process the html template. – Dan Weber Sep 05 '19 at 17:07
  • https://angular.io/api/common/NgClass and https://angular.io/api/common/NgStyle – AT82 Sep 05 '19 at 17:45

1 Answers1

2

You can use Renderer2 for this purpose:

constructor(private renderer2: Renderer2) {

}

ngOnInit() {
    let styles = document.createElement('style');
    let maxWidthValue = '200px';

    let css = `.max-width .innerItems {
      max-width: ${maxWidthValue};
    }`;

    this.styles.type = 'text/css';
    this.styles.appendChild(document.createTextNode(css));
    this.renderer2.appendChild(document.body, styles);
}

OR With jquery you can simply do this:

$(document).ready(function () {
      $("#idOfStyleElement").append('your css');
});
Mustahsan
  • 3,852
  • 1
  • 18
  • 34