Lesson 5: Advanced Angular Concepts

Lesson 5: Advanced Angular Concepts

This lesson covers Drag & Drop, Charts, File Upload, Role-Based Authentication, and Custom Pipes with Parameters. Each example consists of ~200 lines of code, followed by a five-point explanation.


Example 1: Drag & Drop Feature

Implements drag-and-drop functionality using Angular Material CDK DragDrop.

Code:

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { DragDropModule } from '@angular/cdk/drag-drop';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, DragDropModule],
  bootstrap: [AppComponent]
})
export class AppModule { }
// app.component.ts
import { Component } from '@angular/core';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  items = ['Item 1', 'Item 2', 'Item 3', 'Item 4'];

  drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.items, event.previousIndex, event.currentIndex);
  }
}
<!-- app.component.html -->
<h2>Drag & Drop List</h2>
<div cdkDropList (cdkDrop)="drop($event)">
  <div *ngFor="let item of items" cdkDrag>{{ item }}</div>
</div>
/* app.component.css */
div[cdkDrag] {
  padding: 10px;
  margin: 5px;
  background: lightgray;
  cursor: grab;
}

Explanation:

  1. CDK DragDropModule: Enables drag-and-drop without external libraries.

  2. Directive-Based Dragging: cdkDrag makes items draggable.

  3. Drop Event Handling: moveItemInArray() rearranges the list dynamically.

  4. Real-Time UI Updates: Dragged elements instantly re-order in the list.

  5. Minimal Configuration: No external dependencies required.


Example 2: Chart Visualization with Angular

Displays dynamic charts using ngx-charts.

Code:

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgxChartsModule } from '@swimlane/ngx-charts';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, NgxChartsModule],
  bootstrap: [AppComponent]
})
export class AppModule { }
// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  data = [
    { name: 'Apples', value: 50 },
    { name: 'Bananas', value: 30 },
    { name: 'Oranges', value: 20 }
  ];
}
<!-- app.component.html -->
<ngx-charts-bar-vertical [results]="data" [scheme]="'cool'" [xAxis]="true" [yAxis]="true">
</ngx-charts-bar-vertical>

Explanation:

  1. ngx-charts Module: A simple yet powerful library for visualizing data.

  2. Data Binding: results dynamically updates chart values.

  3. Customization: Supports different color schemes, axes, and labels.

  4. Scalability: Works for various chart types (bar, line, pie).

  5. Interactivity: Users can hover to view tooltips dynamically.


Example 3: File Upload with Progress Bar

Handles file uploads and shows a progress bar.

Code:

// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  fileName = '';
  progress = 0;

  onFileSelected(event: any) {
    const file = event.target.files[0];
    if (file) {
      this.fileName = file.name;
      this.uploadFile(file);
    }
  }

  uploadFile(file: File) {
    this.progress = 0;
    const interval = setInterval(() => {
      if (this.progress >= 100) clearInterval(interval);
      else this.progress += 10;
    }, 300);
  }
}
<!-- app.component.html -->
<input type="file" (change)="onFileSelected($event)">
<p>{{ fileName }}</p>
<progress [value]="progress" max="100"></progress>

Explanation:

  1. Event Binding: onFileSelected() captures file input changes.

  2. Simulated Upload: Progress bar updates every 300ms to mimic real uploads.

  3. User Feedback: Displays the file name and progress percentage.

  4. Minimal UI: Uses basic HTML progress for simplicity.

  5. Future Scalability: Can be integrated with backend APIs.


Example 4: Role-Based Authentication

Implements role-based access control in Angular.

Code:

// auth.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private userRole = 'guest';

  login(role: string) {
    this.userRole = role;
  }

  getRole() {
    return this.userRole;
  }
}
// app.component.ts
import { Component } from '@angular/core';
import { AuthService } from './auth.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(public authService: AuthService) {}

  loginAsAdmin() {
    this.authService.login('admin');
  }
}
<!-- app.component.html -->
<button (click)="loginAsAdmin()">Login as Admin</button>
<p *ngIf="authService.getRole() === 'admin'">Admin Access Granted!</p>

Explanation:

  1. AuthService Encapsulation: Centralizes role-based access logic.

  2. Role-Based UI Rendering: *ngIf restricts content visibility.

  3. Login Simulation: Updates user role dynamically.

  4. Scalable: Supports multiple roles (guest, user, admin).

  5. Security Implementation: Can extend to backend JWT authentication.


Example 5: Custom Pipe with Parameters

Creates a pipe that formats numbers dynamically.

Code:

// currency.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'currencyFormat'
})
export class CurrencyPipe implements PipeTransform {
  transform(value: number, currencySymbol: string = '$', decimalPlaces: number = 2): string {
    return `${currencySymbol}${value.toFixed(decimalPlaces)}`;
  }
}
<!-- app.component.html -->
<p>{{ 1234.5 | currencyFormat:'€':1 }}</p>  <!-- Output: €1234.5 -->
<p>{{ 99.99 | currencyFormat:'$':2 }}</p>  <!-- Output: $99.99 -->

Explanation:

  1. Custom Pipe Creation: Implements PipeTransform to modify values.

  2. Dynamic Parameters: Accepts a currency symbol and decimal places.

  3. Reusable Formatting: Works across multiple components.

  4. Improved Readability: Outputs cleaner, well-formatted currency values.

  5. Performance Optimized: Runs efficiently with Angular change detection.


Summary

These five Angular examples cover drag & drop, chart visualization, file uploads, role-based authentication, and custom pipes, essential for modern web applications.