Most Angular applications are composed of a majority of components and just a few directives if any. Today, I’d like to show you an example where a directive makes much more sense than a component.
Consider the following component template:
We have created a component tied to one single HTML element (button), and all the logic in that template is about changing attribute values (for the isActive
class and the disabled
attribute).
To achieve this, we needed three specialized inputs that resulted in a loss of reusability:
The above isn’t ideal because:
- Our button can only display text, not any HTML (so no icons, for instance)
- Our button assumes that its state always depends on
saved
andhasError
, but what if we want to add a third variable to the mix for other use cases?
Let’s create a directive instead:
Which would be used like so:
This implementation is a lot better because:
- It would work with any HTML element, not just buttons (assuming the element supports
disabled
properly) - The button can display anything, not just text
- The criteria for
isActive
to be true depends on the use case and isn’t tied to justsaved
andhasError
.
The point here is that using a directive in that scenario made our code more flexible, and as a result, more reusable. That’s why popular component libraries rely heavily on directives rather than components. Here’s an example from the Angular Material documentation:
You can see that mat-button
is a directive, not a component. That way, it can be used with a button
or an a
tag. You can find the example code of this post on Stackblitz.
Think about this the next time you’re tempted to create a component with one or two lines of HTML in its template. Most likely, what you need instead is a directive.
Check out this tutorial for another example of a directive that makes perfect sense instead of using a component.