In this tutorial, we'll walk through the process of creating an interactive draggable range selector chart using Angular and Chart.js. This chart allows users to visually select a range by dragging two vertical lines across the chart canvas. By the end of this tutorial, you'll have a better understanding of how to implement such a feature-rich chart in your Angular applications.
Live DemoPrerequisitesBefore we begin, ensure you have the following prerequisites installed:
Node.js and npm (Node Package Manager)
Angular CLI (Command Line Interface)
Getting StartedLet's start by creating a new Angular application. Open your terminal and run the following command:
ng new draggable-range-selector-chart
Install Chart.js and its types for TypeScript support:
npm install chart.js@^3.7.0
npm install @types/chart.js@^3.6.0 --save-dev
Implementing the Draggable Range Selector ChartStep 1: HTML StructureOpen the app.component.html file and define the HTML structure for our chart component:
<h1>Draggable Range Selector Chart</h1>
<div style="position: relative;">
<canvas #chartCanvas width="800" height="300"></canvas>
<div id="customTooltip" style="display: none; position: absolute; background-color: rgba(0, 0, 0, 0.7); color: white; padding: 5px; border-radius: 5px;"></div>
</div>
In this structure, we have a title and a container div with a canvas element (
#chartCanvas) for rendering the chart. Additionally, there's a hidden tooltip div (
#customTooltip) for displaying information on hover.
Step 2: Angular Component LogicOpen the app.component.ts file and implement the Angular component logic:
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
import Chart, { ChartData, ChartOptions, Plugin } from 'chart.js/auto';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
@ViewChild('chartCanvas') chartCanvas!: ElementRef;
chart: Chart | null = null;
verticalLineX1: number = 0;
verticalLineX2: number = 0;
isDragging1: boolean = false;
isDragging2: boolean = false;
offsetX1: number = 0;
offsetX2: number = 0;
ngAfterViewInit(): void {
this.initializeChart();
}
}
This component class initializes the Chart.js chart, handles mouse events for dragging the vertical lines, and updates the chart accordingly.
Step 3: Chart InitializationImplement the
initializeChart method to initialize the Chart.js chart:
initializeChart(): void {
const ctx = this.chartCanvas.nativeElement.getContext('2d');
if (!ctx) return;
const chartOptions: ChartOptions = this.createChartOptions();
const chartData: ChartData = this.createChartData();
this.chart = new Chart(ctx, {
type: 'line',
data: chartData,
options: chartOptions,
plugins: this.createChartPlugins(),
});
this.setInitialLinePositions();
this.setupEventListeners();
}
This method creates a new Chart.js instance with the specified options, data, and plugins. It also sets initial positions for the vertical lines and sets up event listeners for mouse events.
Step 4: Chart Options and DataImplement methods for creating chart options and data:
createChartOptions(): ChartOptions {
return {
scales: {
x: { type: 'category', position: 'bottom' },
y: { beginAtZero: true },
},
plugins: {
legend: { display: false },
tooltip: { enabled: false },
},
interaction: { intersect: false },
};
}
createChartData(): ChartData {
return {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
data: [12, 19, 3, 5, 2, 3, 10],
borderColor: 'blue',
borderWidth: 1,
fill: false,
}],
};
}
These methods define the options and data for the Chart.js chart.
Step 5: Event HandlingImplement event handling methods for mouse events:
setupEventListeners(): void {
const canvas = this.chart?.canvas;
if (!canvas) return;
canvas.addEventListener('mousedown', this.onMouseDown.bind(this));
canvas.addEventListener('mousemove', this.onMouseMove.bind(this));
canvas.addEventListener('mouseup', this.onMouseUp.bind(this));
}
These methods handle mouse events for dragging the vertical lines and updating the chart accordingly.
Step 6: Additional FunctionalityImplement additional functionality as needed, such as drawing vertical lines, updating tooltips, etc.
Step 7: StylingApply CSS styles to customize the appearance of the chart and tooltip as desired.
ConclusionIn this tutorial, we've learned how to build a draggable range selector chart in Angular using Chart.js. We've implemented the necessary HTML structure, Angular component logic, and Chart.js functionality to create an interactive chart that allows users to select a range visually. With this knowledge, you can further customize and enhance the chart to suit your specific requirements.
To see the full implementation and explore further customization options, you can check out the code repository:
Go to Github Repo Feel free to experiment with the code and adapt it to your own projects. Happy charting!
If you found this tutorial helpful and would like to support my work, consider buying me a book or supporting me by sharing the article.
👉👉 📔
[Buy Me a Book] 👈 👈