Dynamically add classes to host elements using @HostBinding in Angular?

Armeen Harwood picture Armeen Harwood · Nov 29, 2017 · Viewed 8.8k times · Source

Question:

Is it possible to use @HostBinding in such a way to add, remove, or toggle classes on a host element and not remove preexisting classes, in particular when the classes need to be dynamically toggled ?

For example, this will add light class and be non-disruptive to the previous classes;however, light cannot be dynamic.

Imagine this rendered dom node:

<div [classToggler] class="someClasses1 someClasses2' ></div>

With this controller:

@HostBinding('class.light') isLight = theme === 'light';  // true
ngOnInit() {
  this.store.select('classToggler').subscribe((className) => {
      this.theme = className || 'light'
  });

}

Where as this example controller, will add the light class dynamically but to my knowledge will remove other classes on host element.

@HostBinding('class') theme;

ngOnInit() {
  this.store.select('classToggler').subscribe((className) => {
      this.theme = className || 'light'
  });
}

In the end the second example will re-render the dom element to look like this:

<div [classToggler] class="light'></div>

And therefore, remove the previous classes, which isn't desired. Any ideas on how to get the best of both worlds?

Answer

Sunil Singh picture Sunil Singh · Oct 8, 2018

Change this line

@HostBinding('class') theme;

to

@HostBinding('class') 
get themeClass(){
  return this.theme;
};