Lesson 5: Advanced Angular Concepts
Table of contents
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:
CDK DragDropModule: Enables drag-and-drop without external libraries.
Directive-Based Dragging:
cdkDrag
makes items draggable.Drop Event Handling:
moveItemInArray()
rearranges the list dynamically.Real-Time UI Updates: Dragged elements instantly re-order in the list.
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:
ngx-charts Module: A simple yet powerful library for visualizing data.
Data Binding:
results
dynamically updates chart values.Customization: Supports different color schemes, axes, and labels.
Scalability: Works for various chart types (bar, line, pie).
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:
Event Binding:
onFileSelected()
captures file input changes.Simulated Upload: Progress bar updates every 300ms to mimic real uploads.
User Feedback: Displays the file name and progress percentage.
Minimal UI: Uses basic HTML
progress
for simplicity.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:
AuthService Encapsulation: Centralizes role-based access logic.
Role-Based UI Rendering:
*ngIf
restricts content visibility.Login Simulation: Updates user role dynamically.
Scalable: Supports multiple roles (
guest
,user
,admin
).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:
Custom Pipe Creation: Implements
PipeTransform
to modify values.Dynamic Parameters: Accepts a currency symbol and decimal places.
Reusable Formatting: Works across multiple components.
Improved Readability: Outputs cleaner, well-formatted currency values.
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.