Briefly speaking, Angular has 3 types of directives:
- Components
- Attribute directives - Change the style or behavior of an element, component, or another directive. You may know NgClass, NgStyle, and NgModel.
- Structural directives - Manipulate the DOM layout by adding and removing DOM elements. You may know *ngIf, *ngFor, *ngSwitch.
Only structural directives are prepended by an asterisk (*).
Structural directives wrap the element in an ng-template
element, that adds and removes its content from the Document Object Model (DOM).
Main difference between structural and attribute directives
The main difference between structural and attribute directives is that the former changes the structure of the DOM by adding and removing content.
The latter only hides or shows content in the UI but the content is always available in the DOM.
Use the dev tool to see the DOM tree and how it changes when you use either of them.
Pros & Cons
Often you will just use either structural or attribute directives for a specific scope.
However, when you can choose, you should be aware of the advantages and disadvantages of the two directives.
Broadly speaking, attribute directives are less performance-intensive when they hide and show elements. However, behind the scene, they always create the DOM branch of the elements they should render or hide.
On the other side, structural directives don't always create a DOM branch. This might decrease resources need in the beginning. However, they might be less efficient when an element changes often because the element gets destroyed and re-created in the DOM.
Top comments (0)