Adding Static Attributes to the Host Element in Angular
There are times when we need to add a static class to our host element. Angular comes with two ways to implement this — the HostBinding
decorator and the Component
decorator host
property.
There is a statement in the Angular docs that says:
Consider preferring the
@HostListener
and@HostBinding
to thehost
property of the@Directive
and@Component
decorators.
Using the HostBinding
decorator, we can add our class
as follows:
Sure, it’ll work. In fact, if we examine the source code, we’ll find that Angular produces the change detection phase code, despite the fact that our class
supposed to be “static”:
Using this technique, we add redundant code and work to our app. A better approach in this case is to use the Component
decorator host
property:
Angular will now add the class once during the creation phase.
Follow me on Medium or Twitter to read more about Angular and JS!