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

1.9k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

@HostBinding('class') & @HostBinding('attr.class') have the same net effect and using either of these will yield the same result. @HostBinding can be used to bind to any class, property or attribute on a host element. Which syntax you use will be determined by what you are trying to do.

If you are trying to dynamically change a data- attribute then you will need to use @HostBinding('attr.data-special').

If you are want to change the disabled state of the element then you would use @HostBinding('disabled').

You can also bind to individual classes using @HostBinding('class.myClass') or bind inline styles such as @HostBinding('style.color').