Comprehending the Objective
I'm now fully grasping the need for an Angular-powered, real-time dashboard. The core focus is clear: to leverage Chart.js for data visualization within the Angular framework. This is the starting point.
Adding Real-time Updates
I've been thinking about incorporating RxJS to simulate real-time data flows. ng2-charts seems the best option for managing the charting lifecycle within Angular. For the dashboard, I'll need Angular, Chart.js, RxJS, and some basic styling. The project will start with the creation of the project and installation of dependencies.
Refining the Visualization
I'm now zeroing in on the specifics of the data visualization. I've decided to employ a bar chart for categorical comparisons and a doughnut chart for representing parts-to-whole relationships. My coding draft includes the core dependencies: chart.js and ng2-charts, with the service utilizing an RxJS Interval for the real-time simulation, specifically tracking server CPU load and sales. I've selected a BehaviorSubject for emitting updates. I also realized I need to import the BaseChartDirective and implement a ChartConfiguration within the component, with the update() method essential for real-time updates. I realized that ng2-charts handles canvas destruction, a key consideration for efficient memory management.
Optimizing Data Handling
I'm now implementing the sliding window technique for the line chart, pushing new data and labels while shifting out the old to achieve smoother real-time rendering. I've also finalized the project structure and installed required dependencies.
The DashboardService is being structured to use interval(2000) to emit new values. I've chosen standalone components. The service is now structured to return an Observable that emits CPU and Sales data. Finally, I'm working out the logic for each of the charts and data updates. The implementation will include the service, chart 1 with the sliding window technique, chart 2 for sales, and chart 3 for the static values.
Concluding the Project
I'm now putting the finishing touches on the project. I'm adding clear run instructions and explanations for RxJS implementation. I'm also ensuring responsiveness with CSS Grid and incorporating ngOnDestroy to prevent memory leaks by unsubscribing from the interval. All the necessary components are present: Angular, Chart.js, RxJS, and real-time updates. The project adheres to the given constraints.
Completing the Integration
I'm wrapping up the final touches, ensuring easy usability for others. I've compiled all the code for the essential files (component.ts, html, and css) into a ready-to-use format. This makes it straightforward for anyone to replicate and implement the real-time dashboard I've created. This integration represents the end of the line.
This guide provides a complete implementation of a real-time dashboard using Angular (Standalone Components), Chart.js (via ng2-charts), and RxJS for data streaming.
Prerequisites
- Create a new Angular project:
ng new realtime-dashboard --standalone
cd realtime-dashboard
- Install the charting libraries:
npm install chart.js ng2-charts
1. Application Configuration
First, register the Chart.js providers.
src/app/app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideCharts, withDefaultRegisterables } from 'ng2-charts';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
// Register Chart.js modules
provideCharts(withDefaultRegisterables())
]
};
2. The Real-Time Data Service (RxJS)
This service simulates a WebSocket or Server-Sent Event stream using RxJS interval and map.
src/app/services/data.service.ts
import { Injectable } from '@angular/core';
import { Observable, interval, map, shareReplay } from 'rxjs';
export interface ServerStats {
cpuUsage: number;
memoryUsage: number;
activeUsers: number;
requestsPerSecond: number;
}
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor() { }
// Simulates a socket connection emitting data every 1 second
getServerStats(): Observable<ServerStats> {
return interval(1000).pipe(
map(() => ({
cpuUsage: Math.floor(Math.random() * (100 - 20) + 20), // Random 20-100
memoryUsage: Math.floor(Math.random() * (100 - 40) + 40), // Random 40-100
activeUsers: Math.floor(Math.random() * 5000),
requestsPerSecond: Math.floor(Math.random() * 200)
})),
shareReplay(1) // Share stream among subscribers
);
}
}
3. The Dashboard Component
This component subscribes to the data stream and updates the Chart.js datasets dynamically.
src/app/dashboard/dashboard.component.ts
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BaseChartDirective } from 'ng2-charts';
import { ChartConfiguration, ChartOptions, ChartType } from 'chart.js';
import { Subscription } from 'rxjs';
import { DataService, ServerStats } from '../services/data.service';
@Component({
selector: 'app-dashboard',
standalone: true,
imports: [CommonModule, BaseChartDirective],
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css'] // or .scss
})
export class DashboardComponent implements OnInit, OnDestroy {
// Access to the chart instance to force updates
@ViewChild(BaseChartDirective) chart?: BaseChartDirective;
private streamSub!: Subscription;
// --- Chart 1: Line Chart (CPU History) ---
public lineChartData: ChartConfiguration<'line'>['data'] = {
labels: [],
datasets: [
{
data: [],
label: 'CPU Usage %',
fill: true,
tension: 0.5,
borderColor: 'rgba(75,192,192,1)',
backgroundColor: 'rgba(75,192,192,0.2)'
}
]
};
public lineChartOptions: ChartOptions<'line'> = {
responsive: true,
animation: false, // Disable generic animation for smoother real-time updates
scales: {
y: { beginAtZero: true, max: 100 }
}
};
// --- Chart 2: Bar Chart (Resource Comparison) ---
public barChartData: ChartConfiguration<'bar'>['data'] = {
labels: ['CPU', 'Memory'],
datasets: [ { data: [0, 0], label: 'Resource Load %', backgroundColor: ['#ff6384', '#36a2eb'] } ]
};
public barChartOptions: ChartOptions<'bar'> = { responsive: true, scales: { y: { max: 100 }} };
// --- Stats for Cards ---
public currentStats: ServerStats = {
cpuUsage: 0, memoryUsage: 0, activeUsers: 0, requestsPerSecond: 0
};
constructor(private dataService: DataService) {}
ngOnInit(): void {
// Seed initial time labels for the line chart (last 10 seconds)
const now = new Date();
for (let i = 10; i > 0; i--) {
this.lineChartData.labels?.push(new Date(now.getTime() - i * 1000).toLocaleTimeString());
this.lineChartData.datasets[0].data.push(0);
}
// Subscribe to Real-time Stream
this.streamSub = this.dataService.getServerStats().subscribe((stats) => {
this.currentStats = stats;
this.updateCharts(stats);
});
}
private updateCharts(stats: ServerStats): void {
const timeLabel = new Date().toLocaleTimeString();
// 1. Update Line Chart (Sliding Window logic)
if (this.lineChartData.labels && this.lineChartData.datasets[0].data) {
// Remove oldest
this.lineChartData.labels.shift();
this.lineChartData.datasets[0].data.shift();
// Add newest
this.lineChartData.labels.push(timeLabel);
this.lineChartData.datasets[0].data.push(stats.cpuUsage);
}
// 2. Update Bar Chart (Direct replacement)
this.barChartData.datasets[0].data = [stats.cpuUsage, stats.memoryUsage];
// 3. Trigger Chart.js update
this.chart?.update();
}
ngOnDestroy(): void {
if (this.streamSub) this.streamSub.unsubscribe();
}
}
4. The Template (HTML)
Uses a simple grid layout to display stats and charts.
src/app/dashboard/dashboard.component.html
<div class="dashboard-container">
<header>
<h1>🚀 Angular Real-Time Monitor</h1>
<span class="status-pulse">Live</span>
</header>
<!-- KPI Cards -->
<div class="kpi-grid">
<div class="card">
<h3>Active Users</h3>
<div class="value">{{ currentStats.activeUsers | number }}</div>
</div>
<div class="card">
<h3>Req / Sec</h3>
<div class="value">{{ currentStats.requestsPerSecond }}</div>
</div>
<div class="card warning" [class.danger]="currentStats.cpuUsage > 80">
<h3>CPU Load</h3>
<div class="value">{{ currentStats.cpuUsage }}%</div>
</div>
</div>
<!-- Charts Grid -->
<div class="charts-grid">
<!-- Line Chart -->
<div class="chart-wrapper">
<h2>CPU Timeline</h2>
<canvas baseChart
[data]="lineChartData"
[options]="lineChartOptions"
type="line">
</canvas>
</div>
<!-- Bar Chart -->
<div class="chart-wrapper">
<h2>System Resources</h2>
<canvas baseChart
[data]="barChartData"
[options]="barChartOptions"
type="bar">
</canvas>
</div>
</div>
</div>
5. Styles (CSS)
Basic styling to make the dashboard responsive and visually appealing.
src/app/dashboard/dashboard.component.css
/* Layout */
.dashboard-container {
padding: 20px;
font-family: 'Segoe UI', sans-serif;
max-width: 1200px;
margin: 0 auto;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
}
/* KPI Cards */
.kpi-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.card {
background: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
text-align: center;
}
.card h3 { color: #666; margin: 0 0 10px; font-size: 0.9rem; }
.card .value { font-size: 2rem; font-weight: bold; color: #333; }
.card.warning .value { color: #f39c12; }
.card.danger .value { color: #e74c3c; }
/* Charts */
.charts-grid {
display: grid;
grid-template-columns: 2fr 1fr; /* Line chart takes more space */
gap: 20px;
}
@media (max-width: 768px) {
.charts-grid { grid-template-columns: 1fr; }
}
.chart-wrapper {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.05);
height: 400px;
}
.chart-wrapper h2 { margin-top: 0; font-size: 1.1rem; color: #444; }
/* Pulse Animation */
.status-pulse {
background: #2ecc71;
color: white;
padding: 5px 12px;
border-radius: 20px;
font-size: 0.8rem;
box-shadow: 0 0 0 0 rgba(46, 204, 113, 1);
animation: pulse-green 2s infinite;
}
@keyframes pulse-green {
0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(46, 204, 113, 0.7); }
70% { transform: scale(1); box-shadow: 0 0 0 10px rgba(46, 204, 113, 0); }
100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(46, 204, 113, 0); }
}
6. Integrate into App Route
Finally, update your app.component.html or app.routes.ts to show the component.
src/app/app.routes.ts
import { Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
export const routes: Routes = [
{ path: '', component: DashboardComponent }
];
Key Implementation Details
- RxJS Interval: The
DataService uses interval(1000) to create a "heartbeat." In a real app, this would likely be a webSocket subject.
- Sliding Window: In
updateCharts, for the Line Chart, we shift() (remove the first item) and push() (add a new item). This keeps the chart moving without compressing the data or running out of memory.
- Animation Optimization: Note
animation: false in lineChartOptions. When updating data every second, defaults Chart.js animations can look "bouncy" or overlapping. Turning them off creates a medical-monitor style smooth sweep.
@ViewChild: This is critical. Angular's change detection updates the data object bindings, but Chart.js needs to be told to re-render the canvas pixels. Calling this.chart?.update() triggers this process.