1

I have a component that uses @HostBinding to set a class:

@HostBinding('class.dark-1') true;

Which works fine. However, now I need to create a function in my component to change the class dynamically.

For example, from dark-1 to light-2 when a button in the component is clicked.

I know how to create the function and call it from a button, but how do I change the class in the hostbinding and refresh the UI with the new class?

Steve
  • 14,401
  • 35
  • 125
  • 230

2 Answers2

2

You can toggle a clicked flag when clicking the button, and set the classes with getters:

@HostBinding("class.dark-1") public get classDark1() {
    return !this.clicked;
}

@HostBinding("class.light-2") public get classLight2() {
    return this.clicked;
}

private clicked = false;

public onClick() {
    this.clicked = true;
}
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
0

Sinply give it a property name:

@HostBinding('class.dark-1') isDark = true;

Then you can change it:

this.isDark = false;

Or change entire className:

@HostBinding('class') className = 'dark-1';

this.className = 'light-1';
funkizer
  • 4,626
  • 1
  • 18
  • 20
  • can you do a similar thing with attributes that might contain a value? – roberto tomás Jun 13 '19 at 21:59
  • For any attribute you can do `@HostBinding('attr.data-my-attribute') myDataAttr = 'value';` Having said that, I don't know why you would want to do this with Angular. :) Maybe if you're making a web-component that's to be used outside an Angular app, then yes, otherwise I see no reason... – funkizer Jul 20 '21 at 16:45