Built-in Directives

Loading concept...

๐ŸŽญ 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

  1. Use modern syntax (@if, @for, @switch) for new projects
  2. Prefer NgClass over NgStyle for maintainability
  3. Always use track in @for loops for performance
  4. NgTemplateOutlet is your friend for reusable UI patterns
  5. Donโ€™t mix *ngIf and *ngFor on 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! ๐Ÿš€

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.