A few months back, I suggested that Angular developers don’t use enough directives and use too many components. This is because components quickly become second nature when writing Angular code, while directives are less common and, as a result, can feel more complex at first.
The critical difference between components and directives is that components have an HTML template, and directives don’t. That lack of a template can be slightly uncomfortable at first unless you realize that you still have access to HTML attribute bindings but in a different manner.
For instance, let’s consider the following component template:
Those two bindings used in a directive would become:
In other words, when you see a binding with []
in a component, @HostBinding()
does the same thing in a directive.
For example: [id]="testId"
in a component template becomes @HostBinding("id") testId;
in a directive class.
The same goes for event listeners. This component (click)
binding:
Becomes the following in a directive:
As a recap: []
become @HostBinding
and ()
become @HostListener
. Those are the same thing. That’s it. No template is needed. For a real-life example of a custom directive, feel free to take a look at this tutorial of mine.