What is the difference between structural and attribute directives?
Angular directives are classes that add extra behavior to elements in your Angular applications. They are broadly categorized into structural and attribute directives, each serving distinct purposes related to modifying the DOM structure or changing an element's appearance/behavior.
Structural Directives
Structural directives are responsible for changing the DOM layout by adding, removing, or manipulating elements. They are easily recognizable by the asterisk (*) prefix before their name. When Angular encounters a structural directive, it treats it as a template, wrapping the host element and its children in an <ng-template> tag, then using that template to render or remove sections of the DOM, thus altering the structure itself.
- <code>*ngIf</code>: Conditionally adds or removes an element from the DOM.
- <code>*ngFor</code>: Renders a list of items by iterating over a collection and creating a new element for each item.
- <code>*ngSwitch</code>: Conditionally displays one of several possible elements based on a switch value.
<div *ngIf="isLoggedIn">
Welcome, user!
</div>
<div *ngFor="let item of items">
{{ item.name }}
</div>
Attribute Directives
Attribute directives are used to change the appearance or behavior of an existing DOM element, component, or another directive. They interact directly with the host element they are applied to, modifying its properties (e.g., styles, classes) or adding new behavior without altering the DOM structure itself. They do not have the asterisk (*) prefix.
- <code>ngClass</code>: Dynamically adds or removes CSS classes from an element.
- <code>ngStyle</code>: Dynamically sets inline styles on an element.
- Custom attribute directives: Can be created to encapsulate reusable DOM manipulation logic, like highlighting an element on hover.
<p [ngClass]="{'active': isActive, 'highlight': isHighlight}">
This text might be active and highlighted.
</p>
<p [ngStyle]="{'color': myColor, 'font-size': mySize + 'px'}">
This text has dynamic styles.
</p>
Key Differences (Summary)
| Feature | Structural Directives | Attribute Directives |
|---|---|---|
| Purpose | Adds/removes/manipulates elements in the DOM (changes structure) | Changes the appearance or behavior of an existing element (changes attributes/styles) |
| Syntax | Starts with an asterisk (<code>*</code>) | Applied as an attribute (no <code>*</code>) |
| DOM Impact | Modifies the DOM layout (adds/removes elements, creates <code><ng-template></code>) | Does not modify the DOM layout (operates on existing elements) |
| Examples | <code>*ngIf</code>, <code>*ngFor</code>, <code>*ngSwitch</code> | <code>ngClass</code>, <code>ngStyle</code>, Custom Highlight Directive |