Sunday, March 2, 2025

#4 Session 3: Directives, Pipes & Services (2 Hours) Learning Objectives

 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 (ngClassngStyle)

In app.component.ts file Modify:

  1. 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;
    }
    }
2.  Modify app.component.html

<h1> Structural Directives Demo</h1>
<!-- Toggle Button -->
<button (click)="showContent = !showContent">Toggle Content</button>

<!-- Using *ngIf -->
<p *ngIf="showContent">This content is conditionally displayed!</p>

<!-- Using *ngFor -->
<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>
<h2>Attribute Directives Demo</h2>
<p [ngClass]="{'highlight': isHighlighted}">This text changes color.</p>
<p [ngStyle]="{'color': isHighlighted ? 'blue' : 'black'}">Styled text!</p>
<button (click)="toggleHighlight()">Toggle Highlight</button>


3. Modify app.component.css
.highlight {
    color: red;
    font-weight: bold;
  }

4. ng serve


Step 2: Using Attribute Directives (ngClass, ngStyle)

  1. Modify app.component.ts             

import {CommonModule, NgFor, NgIf, NgClass, NgStyle}

@componet decorator modify 
        imports: [CommonModule, NgIf, NgFor, NgClass, NgStyle],
  1. Modify app.component.ts to add a condition:

    export class AppComponent {
      isHighlighted = false;
    
      toggleHighlight() {
        this.isHighlighted = !this.isHighlighted;
      }
    }
    
  2. Update app.component.html with ngClass and ngStyle:

    <p [ngClass]="{'highlight': isHighlighted}">This text changes color.</p>
    <p [ngStyle]="{'color': isHighlighted ? 'blue' : 'black'}">Styled text!</p>
    <button (click)="toggleHighlight()">Toggle Highlight</button>
    
  3. 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

  1. Generate a directive:
    ng generate directive highlight
    
  2. Open highlight.directive.ts and 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';
      }
    }
    
  3. Use the directive in app.component.html:
    <p appHighlight>Hover over me to see the directive in action!</p>
    
  4. Update app.componet.ts file 
    
    import { Component} from '@angular/core';
    import { HighlightDirective } from './highlight.directive'; 
    
  5. @Component ({.....
    
    imports : [NgIf, NgFor, NgClass, NgStyle, HighlightDirective];
    
    ...})
  6. ✅ Run ng serve and 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

  1. Open app.component.ts and modify import , imports[], define variables:
    imports {CommonModule } from '@angular/core;
    imports: [CommonModule, NgIf, NgFor,
    NgClass, NgStyle, CommonModule],
    export class AppComponent { today = new Date(); price = 1234.56; }
  2. Update app.component.html with 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

  1. Generate a pipe:
    ng generate pipe customTitle
    
  2. Open custom-title.pipe.ts and 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();
      }
    }
    
  3. 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

  1. Generate a service:
    ng generate service data
    
  2. Open data.service.ts and modify:
    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root'
    })
    export class DataService {
      private users = ['Alice', 'Bob', 'Charlie'];
    
      getUsers() {
        return this.users;
      }
    }
    
  3. Open app.component.ts and 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();
      }
    }
    
  4. Update app.component.html to 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

#11 @Output

  Understanding @Output() in Angular 19 The @Output() decorator in Angular 19 is used to send data from a child component to a parent co...