Here are the lecture notes for Session 3: Directives, Pipes & Services (2 hours) with a step-by-step hands-on guide.
Session 3: Directives, Pipes & Services (2 Hours)
Learning Objectives
✅ Understand Directives and how to use them in Angular
✅ Learn about Pipes for data transformation
✅ Explore Services and Dependency Injection (DI)
✅ Hands-on practice with Directives, Pipes & Services
1. Understanding Directives (30 mins)
What are Directives?
- Directives are special instructions that modify the DOM or add behavior to elements.
- Three types of directives in Angular:
| Type | Example | Purpose |
|---|---|---|
| Structural Directives | *ngIf, *ngFor, *ngSwitch |
Change the structure of the DOM |
| Attribute Directives | ngClass, ngStyle |
Change the appearance/behavior of an element |
| Custom Directives | appHighlight |
Create reusable custom behaviors |
Step 1: Using Structural Directives (ngIf, ngFor) & Attribute Directives (ngClass, ngStyle)
- import { NgIf, NgFor, NgClass, NgStyle } from '@angular/common';import { Component } from '@angular/core';@Component({selector: 'app-root',imports: [NgIf, NgFor, NgClass, NgStyle],templateUrl: './app.component.html',styleUrl: './app.component.css'})export class AppComponent {title = 'directives';showContent: boolean = true;items = ['Apple', 'Banana', 'Orange', 'Mango'];isHighlighted = false;toggleHighlight() {this.isHighlighted = !this.isHighlighted;}}
3. Modify app.component.css
4. ng serve
Step 2: Using Attribute Directives (ngClass, ngStyle)
Modify app.component.ts
import {CommonModule, NgFor, NgIf, NgClass, NgStyle}@componet decorator modifyimports: [CommonModule, NgIf, NgFor,NgClass, NgStyle],
-
Modify
app.component.tsto add a condition:export class AppComponent { isHighlighted = false; toggleHighlight() { this.isHighlighted = !this.isHighlighted; } } -
Update
app.component.htmlwithngClassandngStyle:<p [ngClass]="{'highlight': isHighlighted}">This text changes color.</p> <p [ngStyle]="{'color': isHighlighted ? 'blue' : 'black'}">Styled text!</p> <button (click)="toggleHighlight()">Toggle Highlight</button> -
Add styles in
app.component.css:.highlight { color: red; font-weight: bold; }
✅ Run ng serve and test the changes!
Step 3: Creating a Custom Directive
- Generate a directive:
ng generate directive highlight - Open
highlight.directive.tsand update the logic:import { Directive, ElementRef, HostListener} from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef) {} @HostListener('mouseenter') onMouseEnter() { this.el.nativeElement.style.backgroundColor = 'yellow'; } @HostListener('mouseleave') onMouseLeave() { this.el.nativeElement.style.backgroundColor = 'white'; } } - Use the directive in
app.component.html:<p appHighlight>Hover over me to see the directive in action!</p> Update app.componet.ts fileimport { Component} from '@angular/core'; import { HighlightDirective } from './highlight.directive';@Component ({..... imports : [NgIf, NgFor, NgClass, NgStyle, HighlightDirective]; ...})✅ Run
ng serveand test the hover effect!
2. Understanding Pipes (30 mins)
What are Pipes?
- Pipes transform output data in the template.
- Example built-in pipes:
| Pipe | Example | Output |
|---|---|---|
| UpperCasePipe | `{{ 'hello' | uppercase }}` |
| LowerCasePipe | `{{ 'HELLO' | lowercase }}` |
| DatePipe | `{{ today | date:'fullDate' }}` |
| CurrencyPipe | `{{ price | currency:'USD' }}` |
Step 4: Using Built-in Pipes
- Open
app.component.tsand modify import , imports[], define variables:
export class AppComponent { today = new Date(); price = 1234.56; }NgClass, NgStyle, CommonModule],imports {CommonModule } from '@angular/core;
imports: [CommonModule, NgIf, NgFor, - Update
app.component.htmlwith pipes:<p>Original: {{ today }}</p> <p>Date Pipe: {{ today | date:'fullDate' }}</p> <p>Uppercase: {{ 'hello world' | uppercase }}</p> <p>Currency Pipe: {{ price | currency:'USD' }}</p>
✅ Run ng serve and see the transformed data!
Step 5: Creating a Custom Pipe
- Generate a pipe:
ng generate pipe customTitle - Open
custom-title.pipe.tsand modify:import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'customTitle' }) export class CustomTitlePipe implements PipeTransform { transform(value: string): string { return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase(); } } - Use the pipe in
app.component.html:<p>{{ 'angular tutorial' | customTitle }}</p>
✅ Run ng serve and see the custom title case pipe in action!
3. Understanding Services & Dependency Injection (30 mins)
What are Services?
- Services handle business logic and data outside components.
- Dependency Injection (DI) allows sharing data across components.
Step 6: Creating & Using a Service
- Generate a service:
ng generate service data - Open
data.service.tsand modify:import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { private users = ['Alice', 'Bob', 'Charlie']; getUsers() { return this.users; } } - Open
app.component.tsand use the service:import { Component } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { users: string[]; constructor(private dataService: DataService) { this.users = this.dataService.getUsers(); } } - Update
app.component.htmlto display users:<h3>Users List</h3> <ul> <li *ngFor="let user of users">{{ user }}</li> </ul>
✅ Run ng serve and see the user list fetched from the service!
4. Summary & Q&A (15 mins)
✅ What We Learned Today:
✔ Directives: *ngIf, *ngFor, ngClass, ngStyle, Custom Directives
✔ Pipes: Built-in & Custom Pipes
✔ Services & Dependency Injection
Next Session: Routing & Navigation ๐
Would you like any additional topics or modifications? ๐

No comments:
Post a Comment