angularangular2-hostbinding

Angular 6 what is the difference between @HostBinding('class') and @HostBinding('attr.class')


I'm inspecting the source code of an Angular 6 project and saw the usage of both @HostBinding('class') and @HostBinding('attr.class'). I changed one of the implementations from @HostBinding('class') to @HostBinding('attr.class') and did not notice any difference in the rendered result. What are the differences between the two and when should I opt for one implementation over the other?


Solution

  • I don't think there is any meaningful difference between the two in the way you use it, but there is one difference on a conceptual level: using 'class' takes the class definition of the element, while 'attr.class' takes the value of the attribute named "class".

    By using just 'class' without attribute, you can then bind specific classes to a boolean, like this:

    @HostBinding('class.blue')
    @Input() blue: boolean;
    

    Then, assuming the HostBinding is defined in a directive called my-directive, you can use this HTML:

    <div my-directive [blue]="true"></my-directive>
    

    And it would result in a div that contains class="blue"

    As for which one you should use in your case, it doesn't really matter. I would go with simply class because it's shorter, but it really doesn't matter in that case.