Search code examples
angularangular2-directives

understanding how @HostBinding works in angular for toggleClass directive


I came across the following angular directive:

import { Directive , HostListener , HostBinding } from '@angular/core';

@Directive({
    selector: '[appDropdown]'
})

export class DropdownDirective {
    @HostBinding('class.open') isOpen = false;

    @HostListener('click') toggleOpen() {
        this.isOpen = !this.isOpen;
    }
}

While surfing code online , basically the code only toggles the open class on the element the directive is used on , so this directive can be used like so:

<ul class="nav navbar-nav navbar-right">
    <li class="dropdown" appDropdown>
        <a href="#" class="dropdown-toggle" role="button">Manage <span class="caret"></span></a>
        <ul class="dropdown-menu">
            <li><a href="#">Save Data</a></li>
            <li><a href="#">Fetch Data</a></li>
        </ul>
    </li>
</ul>

Now what i don't understand is the below line of code in the directive:

 @HostBinding('class.open') isOpen = false;

Whats exactly is it doing and how exactly does it function ? I am not quite understanding the above line of code. can somebody please explain ?


Solution

  • @HostBinding allows you to define a binding for a host element of your directive. As you probably know there's a special binding syntax for the class that looks like this:

    <element [class.class-name]="expression">...</element>
    

    You can read specifics of implementation in How [class] [attr] [style] directives work.

    In your example the li element is the host element and the expression is isOpen so the host binding your referenced essentially defines the following:

    <li class="dropdown" appDropdown [class.open]="isOpen">