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?

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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';

2 Comments

can you do a similar thing with attributes that might contain a value?
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...

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.