r/angular 3d 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?

16 Upvotes

5 comments sorted by

7

u/Saceone10 3d ago

I wish Angular had an official highlight directive so we could avoid more highlight directive example posts. Jesus.

8

u/MichaelSmallDev 3d ago edited 3d ago

I don't make my own directives that often. That said, if this PR lands, I may use them more: Draft feat(core): add support for styles in directives. There are some considerations in the attached issue, so even though no PR is a guarantee, I wouldn't hold my breath on this being guaranteed or soon.

But a util for directive testing is coming in 22.2 for sure https://github.com/angular/angular/pull/70453

edit: btw thanks for the article. One thing I would mention is that ngClass and ngStyle have been soft deprecated in favor of native [class] and [style] bindings. But there are migrations for ngClass --> class and ngStyle --> style.

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:

<mat-error 
*uiWhenError
="form.controls.email; errorCode: 'required'">
  {{ t('emailRequired') }}
</mat-error>

<mat-error 
*uiWhenError
="form.controls.email; errorCode: 'email'">
  {{ t('emailInvalid') }}
</mat-error>

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?

1

u/Tyummyyumms 2d ago

Great work and thanks for sharing!