What are Directives?
Directives are classes that add new behavior to elements in your templates. As a Technical Lead, you can think of them as 'instructions' for the DOM. While components are directives with templates, many directives are used to manipulate the appearance or layout of existing elements. Angular uses them to make static HTML dynamic and responsive to your application state.
- Three Types of Directives
Angular categorizes directives based on how they affect the DOM. Understanding these categories is essential for maintaining a clean architecture.
- Components: Directives with a template. This is the most common type.
- Attribute Directives: Change the appearance or behavior of an element, component, or another directive (e.g.,
ngClass,ngStyle). - Structural Directives: Change the DOM layout by adding and removing DOM elements (e.g.,
*ngIf,*ngFor).
- Structural Directives (The Asterisk Syntax)
Structural directives are easy to recognize because of the asterisk (*) prefix. They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements.
- Attribute Directives
Attribute directives look like regular HTML attributes. They are used to dynamically change the CSS classes or styles applied to an element based on the component's state.
Directive Comparison Table
| Type | Prefix | Purpose | Common Examples |
|---|---|---|---|
| Structural | * | Adds/Removes elements from DOM | *ngIf, *ngFor, *ngSwitch |
| Attribute | [] | Modifies look or behavior | ngClass, ngStyle, ngModel |
| Custom | Varies | Developer-defined behavior | appHighlight, appTooltip |