February 1, 2017

Angular 2 – Set Elements Class with HostBindings

Angular gives you a useful tool to handle manipulations in the components class. The @HostBinding() annotation provides a range of possibilities.The advantage is quite clear, the required logic remains in the components class and is not set in the template file. This makes it easier to test and improves the readability of the template file. In addition, it is the only way to set the CSS class to the host element within the component.

To set the class  use the @HostBinding() annotation either on a boolean property of the class or use a method returning a boolean. The value determines whether the class is set or not. If the value/return is true, the class will be applied to the component DOM Element.

 

The class to be set is specified within the round brackets, prefixed by class. –  it is also possible to specify several classes by combining multiple annotations.

 

Since the class is added to the host element it is necessary to use the :host-selector.

 

I’ve attached a full example with SCSS styles for the toggled class:

 


Can Kattwinkel

Entwickler bei thecodecampus

Comments (1)

  1. Efi says:

    is this.isActive = !this.isActive;
    no this.isActive =! this.isActive;

Leave a Reply

Your email address will not be published. Required fields are marked *