Designing a real-time dashboard
The user is asking for guidance on creating a real-time dashboard in Angular using Chart.js and RxJS. I should outline the project structure, necessary components, services, and how to integrate Chart.js with Angular. I need to consider if I should go with direct Chart.js or the ng2-charts wrapper since they mentioned Chart.js specifically. It makes sense to show both options. I’ll also think about architecture, state management, data sources, and the Angular version, likely 16 or 17+.Creating an Angular dashboard
I'm planning to guide the user through designing an Angular app with real-time charting using Chart.js and ng2-charts. First, I'll outline the architecture, including the structure of modules, components, and services. Next, I’ll cover dependencies and installation steps, followed by creating a data service that utilizes RxJS for real-time data updates, whether through WebSocket or mocked intervals. I'll also discuss integrating the chart component, managing real-time updates, and considering performance aspects like change detection. I’ll provide code examples for app.module.ts, the dashboard component, and the data service.Configuring real-time charting
I need to cover chart configuration options for streaming data, as Chart.js doesn't support streaming natively without a plugin. Instead, I can simulate this by shifting out old points while pushing in new ones. I'll assume we're working with Angular 17 and use ng2-charts for convenience, which works with Chart.js v4.
First, I'll recommend installing the necessary packages with npm. For TypeScript, Chart.js already includes its own types. In the data service, I'll create a Subject to handle metrics and set up a stream that updates every second, mapping the random data appropriately.Setting up WebSocket and dashboard components
For the WebSocket connection, I would establish a socket to receive metrics data, like this: const socket$ = webSocket<Metric>('ws://localhost:8080/metrics');.
In the dashboard component, I’ll create a simple template with two line charts for CPU and memory usage, using ngOnInit to set up the data streams. The LineChartComponent will receive an observable for each metric.
I need to be cautious about mutating the lineChartData and ensure I handle subscriptions properly. I'll mention using takeUntilDestroyed or unsubscribing in ngOnDestroy, while keeping the implementation concise. Lastly, real-time updates will utilize RxJS operators effectively.Designing a dynamic real-time dashboard
The user might want a dynamic dashboard that includes features like multi-stream composition and toggling between chart types. I’ll outline how to achieve this using Angular, RxJS, and ng2-charts.
For the service, I’ll create a RealTimeDataService to manage the data source connection. The dashboard will utilize observables and pass them to the chart components, which will focus solely on presentation. I should set changeDetection to OnPush to minimize performance overhead. To allow dynamic chart updates, I’ll define a configuration array for charts and use *ngFor in the template.
I’ll also ensure to cover memory management with operators like takeUntil and discuss using AsyncPipe vs. direct subscriptions for data binding. Finally, I’ll format the answer into sections for clarity: installation commands, Angular module config, data service, line-chart component, dashboard component, and additional notes. Below is a complete design outline and example implementation for a real‑time Angular dashboard using:
- Angular (any recent version, 14+)
- Chart.js (via
ng2-charts)
- RxJS for real‑time data streams
You can copy/paste pieces into a project.
1. Install dependencies
npm install chart.js ng2-charts rxjs
2. App structure
Recommended architecture:
RealtimeDataService
- Connects to your data source (WebSocket, SSE, polling, etc.)
- Exposes RxJS
Observables for each metric (CPU, memory, etc.)
DashboardComponent
- Uses the service’s streams
- Lays out the dashboard and passes streams to chart components
LineChartComponent (reusable)
- Wraps Chart.js (via
ng2-charts)
- Subscribes to a numeric stream and keeps last N points in the chart
3. Angular module setup
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgChartsModule } from 'ng2-charts';
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { LineChartComponent } from './charts/line-chart.component';
@NgModule({
declarations: [
AppComponent,
DashboardComponent,
LineChartComponent,
],
imports: [
BrowserModule,
NgChartsModule, // ng2-charts (Chart.js wrapper)
],
bootstrap: [AppComponent],
})
export class AppModule {}
4. Real‑time data service (RxJS)
This example uses a mock stream with interval. Replace with WebSocket/SSE/polling as needed.
realtime-data.service.ts:
import { Injectable } from '@angular/core';
import { interval, map, shareReplay } from 'rxjs';
export interface Metrics {
timestamp: number;
cpu: number;
memory: number;
requestsPerSecond: number;
}
@Injectable({ providedIn: 'root' })
export class RealtimeDataService {
// Base stream emitting a new Metrics object every second
private metrics$ = interval(1000).pipe(
map((i) => ({
timestamp: Date.now(),
cpu: this.randomInRange(10, 95),
memory: this.randomInRange(20, 90),
requestsPerSecond: this.randomInRange(50, 200),
})),
shareReplay({ bufferSize: 1, refCount: true })
);
readonly cpu$ = this.metrics$.pipe(map((m) => ({ t: m.timestamp, v: m.cpu })));
readonly memory$ = this.metrics$.pipe(map((m) => ({ t: m.timestamp, v: m.memory })));
readonly rps$ = this.metrics$.pipe(map((m) => ({ t: m.timestamp, v: m.requestsPerSecond })));
private randomInRange(min: number, max: number): number {
return Math.round(min + Math.random() * (max - min));
}
}
If you have a WebSocket backend:
import { webSocket } from 'rxjs/webSocket';
private socket$ = webSocket<Metrics>('wss://your-server/metrics');
readonly metrics$ = this.socket$.pipe(shareReplay(1));
Then derive cpu$', 'memory$ from metrics$ exactly as above.
5. Reusable LineChartComponent
This component:
- Takes an
Observable<{t: number; v: number}> as input
- Maintains a fixed window (e.g., last 50 points)
- Updates a Chart.js line chart in real time
charts/line-chart.component.ts:
import {
Component,
Input,
OnInit,
OnDestroy,
ViewChild,
ChangeDetectionStrategy,
} from '@angular/core';
import { Observable, Subject, takeUntil } from 'rxjs';
import { ChartConfiguration } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
@Component({
selector: 'app-line-chart',
template: `
<div class="chart-card">
<h3>{{ title }}</h3>
<canvas baseChart
[data]="lineChartData"
[options]="lineChartOptions"
[type]="'line'">
</canvas>
</div>
`,
styles: [`
.chart-card {
background: #fff;
border-radius: 8px;
padding: 1rem;
box-shadow: 0 1px 3px rgba(0,0,0,0.08);
height: 100%;
}
canvas {
max-height: 260px;
}
`],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class LineChartComponent implements OnInit, OnDestroy {
@Input() title = '';
@Input() stream$!: Observable<{ t: number; v: number }>;
@Input() maxPoints = 50; // sliding window size
@Input() color = '#42A5F5';
@ViewChild(BaseChartDirective) chart?: BaseChartDirective;
public lineChartData: ChartConfiguration<'line'>['data'] = {
labels: [],
datasets: [
{
data: [],
label: '',
borderColor: this.color,
backgroundColor: 'rgba(66,165,245,0.1)',
pointRadius: 0,
tension: 0.3,
fill: 'origin',
},
],
};
public lineChartOptions: ChartConfiguration<'line'>['options'] = {
responsive: true,
animation: false,
plugins: {
legend: { display: false },
},
scales: {
x: {
ticks: { maxTicksLimit: 6 },
},
y: {
beginAtZero: true,
},
},
};
private destroy$ = new Subject<void>();
ngOnInit(): void {
this.lineChartData.datasets[0].label = this.title;
this.lineChartData.datasets[0].borderColor = this.color;
this.lineChartData.datasets[0].backgroundColor = this.hexToRgba(this.color, 0.08);
this.stream$
.pipe(takeUntil(this.destroy$))
.subscribe((point) => {
const label = new Date(point.t).toLocaleTimeString();
const labels = this.lineChartData.labels as string[];
const data = this.lineChartData.datasets[0].data as number[];
labels.push(label);
data.push(point.v);
// enforce sliding window
if (labels.length > this.maxPoints) {
labels.shift();
data.shift();
}
// Trigger chart update
this.chart?.update();
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
private hexToRgba(hex: string, alpha: number): string {
const m = hex.replace('#', '');
const bigint = parseInt(m, 16);
const r = (bigint >> 16) & 255;
const g = (bigint >> 8) & 255;
const b = bigint & 255;
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}
}
6. Dashboard layout component
dashboard/dashboard.component.ts:
import { Component, ChangeDetectionStrategy } from '@angular/core';
import { RealtimeDataService } from '../services/realtime-data.service';
@Component({
selector: 'app-dashboard',
template: `
<div class="dashboard">
<div class="row">
<div class="card">
<app-line-chart
title="CPU Usage (%)"
[stream$]="data.cpu$"
[color]="'#ef5350'">
</app-line-chart>
</div>
<div class="card">
<app-line-chart
title="Memory Usage (%)"
[stream$]="data.memory$"
[color]="'#66bb6a'">
</app-line-chart>
</div>
<div class="card">
<app-line-chart
title="Requests / Second"
[stream$]="data.rps$"
[color]="'#ffa726'">
</app-line-chart>
</div>
</div>
</div>
`,
styles: [`
.dashboard {
padding: 1rem;
background: #f4f5f7;
min-height: 100vh;
}
.row {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
gap: 1rem;
}
.card {
min-height: 300px;
}
`],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DashboardComponent {
constructor(public data: RealtimeDataService) {}
}
app.component.html:
<app-dashboard></app-dashboard>
7. Making the charts more “dynamic”
Ideas you can layer on with RxJS:
-
Dynamic series from streams
Use combineLatest to plot multiple series on one chart:
import { combineLatest, map } from 'rxjs';
// In a new multi-series chart component or directly in dashboard
readonly cpuAndMem$ = combineLatest([
this.data.cpu$,
this.data.memory$,
]).pipe(
map(([cpu, mem]) => ({ cpu, mem }))
);
-
Throttling/buffering high-frequency streams
this.highFreqStream$
.pipe(
bufferTime(1000), // batch 1s
map(batch => average(batch)),
)
.subscribe(/* update chart */);
-
Dynamic chart configuration from config objects
In DashboardComponent:
charts = [
{ title: 'CPU Usage (%)', stream$: this.data.cpu$, color: '#ef5350' },
{ title: 'Memory Usage (%)', stream$: this.data.memory$, color: '#66bb6a' },
{ title: 'Requests / Second', stream$: this.data.rps$, color: '#ffa726' },
];
Template:
<div class="row">
<div class="card" *ngFor="let c of charts">
<app-line-chart
[title]="c.title"
[stream$]="c.stream$"
[color]="c.color">
</app-line-chart>
</div>
</div>
8. Performance notes
- Use
ChangeDetectionStrategy.OnPush (already shown) to avoid unnecessary CD runs.
- Use
throttleTime, sampleTime, or bufferTime if the backend sends very frequent updates.
- Keep the sliding window reasonably small (
maxPoints 50–300) for smooth rendering.
- For many charts, prefer fewer subscriptions by sharing streams (via
shareReplay).
If you tell me more about your actual data source (e.g., WebSocket format, desired update rate, number of charts), I can adapt this into a more specific implementation for your case.