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
ProductCardComponent
showing product details on an e-commerce site. -
A
ChatMessageComponent
displaying 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 |