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 (3)

  1. Efi says:

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

  2. Peter Kristensen says:

    For me, it’s not working with the provided SCSS syntax for adding style to the host element with class .isActive. If I’m not wrong, you specify style for all SUB element with this class. Instead, add the “&” sign like this:
    :host {
    &.isActive {


    1. Can Kattwinkel says:

      Pardon, you are right this was a typo (fixed). Thanks for your comment!

      Fyi: another way of writing would be .host(.isActive)

Leave a Reply

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