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 |