Search code examples
cssangularinline

Use variables to update internal CSS inside an angular component?


I would like to modify quite a large amount of styles on a page through a customisable panel. When a user clicks an option, the content on the page will completely change based on whatever was clicked.

This cannot be a scenario where a class is appended to a parent element and use CSS/LESS to adjust accordingly. For this scenario (for requirement reasons) the CSS needs to be internal on the angular component HTML.

Is it possible to have a value in the component TS like this:

myNewColour: "red"

That can then be used in an internal style sheet that's inside my angular component.html like this?:

<style>
  .myContainer { background: myNewColour }
</style>

<!-- HTML Content -->
<div class="myContainer"> Stuff </div>

Any help with this would be appreciated! :)


Solution

  • "Internal in the HTML template" is called inline style ;) Apart from that, you can use ngStyle like so

    <tag [ngStyle]="{'background': myNewColour}"></tag>
    

    EDIT if it makes your code too long, what you can do is simply

    let customStyle = {
      'background': this.myNewColour
    };
    

    And in your tag, simply

    <tag [ngStyle]="customStyle"></tag>