Adding Static Attributes to the Host Element in Angular

Netanel Basal
Netanel Basal
Published in
1 min readDec 10, 2021

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 the host 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!

--

--

Netanel Basal
Netanel Basal

Written by Netanel Basal

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.

Responses (2)