In Angular, directives are classes that allow you to manipulate the DOM or component behavior. There are three main types of directives:
π§± 1. Component Directives
-
Technically, components are directives with a template.
-
They control a section of the screen (UI) and encapsulate logic.
✅ Example:
π Real-World Use:
-
A
ProductCardComponentshowing product details on an e-commerce site. -
A
ChatMessageComponentdisplaying individual messages in a chat app.
⚙️ 2. Structural Directives
-
These change the DOM layout by adding or removing elements.
✅ Built-in Examples:
-
*ngIf: Conditionally includes a template. -
*ngFor: Iterates over a list and renders template for each item. -
*ngSwitch: Switches views based on a condition.
π Real-World Use:
π ️ Custom Example:
π¨ 3. Attribute Directives
-
These change the appearance or behavior of an element, component, or directive.
✅ Built-in Examples:
-
ngClass,ngStyle,required, etc.
π Real-World Use:
π ️ Custom Example:
✅ Summary Table
| Type | Purpose | Built-in Examples | Real-world Use Case |
|---|---|---|---|
| Component | UI + behavior + template | Any Angular component | Reusable UI blocks like cards, modals, widgets |
| Structural | Add/remove elements in DOM | *ngIf, *ngFor | Conditional rendering, lists |
| Attribute | Modify element behavior/appearance | ngClass, ngStyle | Highlight, tooltips, dynamic styles |
