Search code examples
javascriptangulartypescriptinnerhtml

How to render inner Css - Angular


I have an object "Content" contains two properties:

Content:{
html:string;
css:string
}

and I need to render a div depending on this object, for the html I could do that using:

<div [innnerHtml]="Content.html"></div>

but I couldn't render the css of the object. Content example:

Content:{
html:"<p>test rendering the object</p> <br> <div class="div1"></div>",
css:"p{color:red} .div1{background-color:black}"
}

Solution

  • The solution for me was appending the style content programmatically, like this:

    ngOnInit() {
      const css = 'a {color: pink;}';
      const head = document.getElementsByTagName('div')[0];
      const style = document.createElement('style');
      style.type = 'text/css';
      style.appendChild(document.createTextNode(css));
      head.appendChild(style);
    }