๐ญ Angularโs Magic Wands: Built-in Directives
Imagine you have a magic coloring book. Some pages appear only when you say the magic word. Other pages change their colors based on your mood. Thatโs exactly what Angular directives do to your web pages!
๐ The Two Families of Magic Wands
In Angularโs magical kingdom, there are two types of magic wands (directives):
graph TD A[๐ญ Built-in Directives] --> B[๐๏ธ Structural] A --> C[๐จ Attribute] B --> D[Change the SHAPE<br>of your page] C --> E[Change the LOOK<br>of elements]
Think of it like this:
- Structural Directives = A magician who can make things APPEAR or DISAPPEAR ๐ช
- Attribute Directives = A painter who changes how things LOOK ๐๏ธ
๐๏ธ Structural Directives: The Shape-Shifters
Structural directives add, remove, or replace elements in your HTML. They literally change the structure of your page!
How to Spot Them
They always start with an asterisk (*) - like a little star! โญ
*ngIf
*ngFor
*ngSwitch
The Magic Behind the Star
When you write *ngIf, Angular secretly transforms it into something bigger. Itโs like shorthand magic!
What you write:
<div *ngIf="showMessage">
Hello!
</div>
What Angular sees:
<ng-template [ngIf]="showMessage">
<div>Hello!</div>
</ng-template>
The * is just a shortcut so you donโt have to write all that extra code!
๐ช @if - The Gatekeeper (Modern Way)
@if decides if something should exist or not. Like a bouncer at a party!
@if (isVIP) {
<div>Welcome to the VIP room! ๐</div>
} @else {
<div>Sorry, VIPs only!</div>
}
Real Example:
@if (user.isLoggedIn) {
<button>Logout</button>
} @else if (user.isGuest) {
<button>Sign Up</button>
} @else {
<button>Login</button>
}
๐ @for - The Cloner (Modern Way)
@for creates copies of things. Like a photocopy machine!
@for (fruit of fruits; track fruit) {
<li>{{ fruit }}</li>
}
The track part helps Angular remember each item. Think of it like giving each clone a name tag!
With Empty State:
@for (item of items; track item.id) {
<div>{{ item.name }}</div>
} @empty {
<div>No items found ๐ข</div>
}
๐ฏ @switch - The Decision Maker (Modern Way)
@switch picks one option from many. Like choosing a door!
@switch (animal) {
@case ('dog') {
<span>๐ Woof!</span>
}
@case ('cat') {
<span>๐ฑ Meow!</span>
}
@default {
<span>๐ค Unknown animal</span>
}
}
๐จ Attribute Directives: The Style Artists
Attribute directives donโt add or remove elements. They just change how existing elements look or behave!
They look like HTML attributes inside square brackets:
[ngClass]
[ngStyle]
๐จ NgClass - The Outfit Changer
NgClass adds or removes CSS classes dynamically. Itโs like having a closet full of outfits you can switch instantly!
Three Ways to Use NgClass
1. String - Single class:
<div [ngClass]="'highlight'">
I'm highlighted!
</div>
2. Array - Multiple classes:
<div [ngClass]="['bold', 'italic']">
Bold AND italic!
</div>
3. Object - Conditional classes:
<div [ngClass]="{
'active': isActive,
'disabled': isDisabled,
'error': hasError
}">
My classes change!
</div>
Real Example - Button States:
<button [ngClass]="{
'btn-primary': !isLoading,
'btn-loading': isLoading,
'btn-disabled': isDisabled
}">
{{ isLoading ? 'Loading...' : 'Submit' }}
</button>
๐๏ธ NgStyle - The Instant Painter
NgStyle changes CSS styles directly. Like having magic paint that changes on command!
Basic Usage
<div [ngStyle]="{
'color': textColor,
'font-size': fontSize + 'px',
'background-color': bgColor
}">
I change colors!
</div>
Dynamic Styling
<div [ngStyle]="{
'width': progress + '%',
'background': progress > 50
? 'green'
: 'orange'
}">
Progress: {{ progress }}%
</div>
๐ค NgClass vs NgStyle
| Use NgClass Whenโฆ | Use NgStyle Whenโฆ |
|---|---|
| Toggling predefined styles | Setting dynamic values |
| You have CSS classes ready | Calculating styles in code |
| Better for maintainability | One-off inline styles |
graph TD A[Need to style?] --> B{Predefined<br>CSS class?} B -->|Yes| C[Use NgClass] B -->|No| D{Dynamic<br>value?} D -->|Yes| E[Use NgStyle] D -->|No| C
๐ NgTemplateOutlet - The Copy-Paste Master
NgTemplateOutlet lets you reuse chunks of HTML in different places. Like a stamp you can use anywhere!
Basic Template
<!-- Define the template -->
<ng-template #greetingTemplate>
<p>Hello, welcome! ๐</p>
</ng-template>
<!-- Use it anywhere -->
<ng-container
*ngTemplateOutlet="greetingTemplate">
</ng-container>
Template with Context (Passing Data)
<!-- Template that accepts data -->
<ng-template #userCard let-name="name"
let-role="role">
<div class="card">
<h3>{{ name }}</h3>
<p>{{ role }}</p>
</div>
</ng-template>
<!-- Use with different data -->
<ng-container
*ngTemplateOutlet="userCard;
context: {name: 'Alice', role: 'Admin'}">
</ng-container>
<ng-container
*ngTemplateOutlet="userCard;
context: {name: 'Bob', role: 'User'}">
</ng-container>
Why Use NgTemplateOutlet?
graph TD A[Same HTML<br>in multiple places?] --> B[Create template] B --> C[Reuse with<br>NgTemplateOutlet] C --> D[โ DRY Code!] C --> E[โ Easy to maintain!] C --> F[โ Pass different data!]
๐๏ธ Legacy Structural Directives
Before Angular introduced @if, @for, and @switch, we used these older versions. Youโll see them in existing codebases!
*ngIf (Legacy Version)
<!-- Old way -->
<div *ngIf="isVisible">
I might appear!
</div>
<!-- With else -->
<div *ngIf="isLoggedIn; else loginTemplate">
Welcome back!
</div>
<ng-template #loginTemplate>
<button>Please login</button>
</ng-template>
*ngFor (Legacy Version)
<li *ngFor="let item of items;
let i = index;
let first = first;
let last = last">
{{ i + 1 }}. {{ item.name }}
<span *ngIf="first">๐ฅ</span>
<span *ngIf="last">๐</span>
</li>
*ngSwitch (Legacy Version)
<div [ngSwitch]="color">
<p *ngSwitchCase="'red'">๐ด Red</p>
<p *ngSwitchCase="'blue'">๐ต Blue</p>
<p *ngSwitchDefault>โ Unknown</p>
</div>
๐ Legacy vs Modern Comparison
| Legacy | Modern | Notes |
|---|---|---|
*ngIf |
@if |
Cleaner syntax |
*ngFor |
@for |
Requires track |
*ngSwitch |
@switch |
No wrapper needed |
๐ฏ Quick Summary
graph TD A[๐ญ Directives] --> B[๐๏ธ Structural] A --> C[๐จ Attribute] B --> D["@if / *ngIf<br>Show or hide"] B --> E["@for / *ngFor<br>Loop & repeat"] B --> F["@switch / *ngSwitch<br>Pick one"] C --> G["[ngClass]<br>Toggle CSS classes"] C --> H["[ngStyle]<br>Inline styles"] C --> I["*ngTemplateOutlet<br>Reuse templates"]
๐ Pro Tips
- Use modern syntax (
@if,@for,@switch) for new projects - Prefer NgClass over NgStyle for maintainability
- Always use
trackin@forloops for performance - NgTemplateOutlet is your friend for reusable UI patterns
- Donโt mix
*ngIfand*ngForon the same element - use<ng-container>!
๐ You Did It!
You now understand Angularโs built-in directives! Remember:
- Structural directives (
*or@) = Change page structure - Attribute directives (
[]) = Change element appearance - Templates = Reusable HTML snippets
Go forth and build amazing Angular apps! ๐