Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 532
Armeen Harwood Avatar asked Nov 29 '17 02:11

Armeen Harwood


People also ask

How do I add a class to my host?

You can simply add @HostBinding('class') class = 'someClass'; inside your @Component class. The className directive may also be used and it is better to avoid using class as a variable name (since you might reference it and change it later). Example: @HostBinding('className') myTheme = 'theme-dark'; .

What is HostBinding and HostListener in Angular?

@HostBinding and @HostListener are two decorators in Angular that can be really useful in custom directives. @HostBinding lets you set properties on the element or component that hosts the directive, and @HostListener lets you listen for events on the host element or component.

What does HostBinding do in Angular?

HostBinding - Declares a host property binding. Angular automatically checks host property bindings during change detection. If a binding changes, it will update the host element of the directive. @HostBinding - will bind the property to the host element, If a binding changes, HostBinding will update the host element.

What is host element in Angular?

To turn an Angular component into something rendered in the DOM you have to associate an Angular component with a DOM element. We call such elements host elements.


1 Answers

Change this line

@HostBinding('class') theme;

to

@HostBinding('class') 
get themeClass(){
  return this.theme;
};
like image 79
Sunil Singh Avatar answered Sep 21 '22 15:09

Sunil Singh