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

2
  • 1
    Why not use css vars for that? you can set there value through JS. Commented May 2, 2018 at 19:31
  • not supported in ie Commented May 2, 2018 at 20:36

3 Answers 3

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).

Sign up to request clarification or add additional context in comments.

Comments

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;

        }

Comments

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.