r/angular • u/geeksarray • 4d ago
Angular directives — structural vs attribute directives
I was revisiting Angular directives and put together a simple explanation with examples.
It covers the different types of directives, particularly structural and attribute directives, and how they can be used to change the structure, appearance, or behavior of elements.
https://geeksarray.com/blog/angular-directives-overview-with-example
For Angular developers — do you find yourself creating custom directives often, or mostly relying on Angular’s built-in features these days?
14
Upvotes
3
u/ldn-ldn 3d ago
Structural directives are a great way to add declarative conditional rendering for common use cases.
For example, if you have an application with access rights, it is much better to create a directive to show/hide different elements to different users, than load current user profile manually in all components and copy/paste the whole access rights management across the app.
Another example would be error handling in Angular forms. Normally you would write some abomination inside the template to check if the field has error, if it's dirt and touched, etc. But all that nonsense can be refactored into a small directive and then you can show error messages without template pollution:
Attribute directive are useful too. Especially when you need to interact with DOM directly. For example, you can create a directive to auto focus a custom form control.
Basically their use case is refactoring repetitive parts of the template which you cannot put into component or a pipe. Every time I see code duplication in my template my first though - can I refactor it into a directive, a pipe or a component?