0

I have many existing classes in my app and want to set the style via code (theming feature).

e.g. <button class="mybutton">click</button>

I need something like:

<style>
    .mybutton{
        background-color: {{company?.buttonBackgroundColor}}!important;
    }
</style>

but of course this doesn't work. What would be a nice solution without replacing all existing classes?

EDIT: Angular 2+, not angular js. sorry

daniel
  • 34,281
  • 39
  • 104
  • 158

3 Answers3

2

I would suggest a different approach for theming. Create a *.css file overriding necessary rules for each theme and dynamically add apropriate stylesheet to DOM when you want to switch theme (take a look at How to load up CSS files using Javascript? to find out how to do that).

nutic
  • 457
  • 2
  • 12
0

In angular, you can just access the element and change it's class. You can do way more things, like change it's properties too, but I think that working with classes is neater. Then, you use add classes to the DOM using:

var myEl = angular.element( document.querySelector( '#div1' ) );
myEl.addClass('alpha');

Here you can find some ideas for it: https://stackoverflow.com/a/30410490/5250103

Also, another good solution would be using conditional classes (ngClass): https://stackoverflow.com/a/16529903/5250103

There he explains:

The ngClass directive will work with any expression that evaluates truthy or falsey, a bit similar to Javascript expressions but with some differences, you can read about here. If your conditional is too complex, then you can use a function that returns truthy or falsey, as you did in your third attempt.

An example given here

ng-class="{'test': obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}"

I don't intend to steal any anwser, but as suggested in comments, this was edited and it is quoting it's authors.

I hope it helps!

Vinggui
  • 134
  • 8
0

For me a good solution was vanilla js:

var selects = document.getElementsByClassName('mybutton')
        for (var i = 0, il = selects.length; i < il; i++) {
            selects[i].style.color = this.company.buttonForegroundColor;

        }
daniel
  • 34,281
  • 39
  • 104
  • 158