### Install ng2-charts
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Install ng2-charts and chart.js using the Angular CLI or npm.
```bash
# Via Angular CLI (auto-configures app.config.ts)
ng add ng2-charts
# Manual install
npm install ng2-charts chart.js --save
```
--------------------------------
### Installation
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/landing/landing.component.html
Install ng2-charts using the Angular CLI schematics.
```APIDOC
## Installation
Install ***ng2-charts*** using the schematics:
```bash
ng add ng2-charts
```
```
--------------------------------
### Full Bar Chart Example with Events and Imperative Update
Source: https://context7.com/valor-software/ng2-charts/llms.txt
This example demonstrates a complete bar chart component using ng2-charts. It includes event handling for clicks and hovers, imperative chart updates by mutating data, and exporting the chart as a PNG image. Ensure Chart.js and ng2-charts are installed.
```typescript
// bar-chart.component.ts — full working example with events and imperative update
import { Component, ViewChild } from '@angular/core';
import { ChartConfiguration, ChartData, ChartEvent } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
@Component({
selector: 'app-bar-chart',
standalone: true,
imports: [BaseChartDirective],
template: `
`,
})
export class BarChartComponent {
@ViewChild(BaseChartDirective) chart: BaseChartDirective<'bar'> | undefined;
public barChartOptions: ChartConfiguration<'bar'>['options'] = {
scales: {
x: {},
y: { min: 10 },
},
plugins: {
legend: { display: true },
datalabels: { anchor: 'end', align: 'end' },
},
};
public barChartData: ChartData<'bar'> = {
labels: ['2006', '2007', '2008', '2009', '2010', '2011', '2012'],
datasets: [
{ data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' },
{ data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B' },
],
};
public chartClicked({ event, active }: { event?: ChartEvent; active?: object[] }): void {
console.log('Clicked:', event, active);
// active contains Chart.js ActiveElement[] with dataset and data indices
}
public chartHovered({ event, active }: { event?: ChartEvent; active?: object[] }): void {
console.log('Hovered:', event, active);
}
public randomize(): void {
// Mutate data array in-place, then call update()
this.barChartData.datasets[0].data = [
Math.round(Math.random() * 100),
59, 80,
Math.round(Math.random() * 100),
56,
Math.round(Math.random() * 100),
40,
];
this.chart?.update();
}
public exportImage(): void {
const dataUrl = this.chart?.toBase64Image();
if (dataUrl) {
const a = document.createElement('a');
a.href = dataUrl;
a.download = 'chart.png';
a.click();
}
}
}
```
--------------------------------
### Install ng2-charts using Schematics
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/landing/landing.component.html
Use the ng add command to install ng2-charts and its dependencies.
```bash
ng add ng2-charts
```
--------------------------------
### Install ng2-charts Schematics
Source: https://github.com/valor-software/ng2-charts/blob/master/libs/ng2-charts-schematics/src/README.md
Install the ng2-charts-schematics package as a development dependency using npm.
```bash
npm install --save-dev ng2-charts-schematics
```
--------------------------------
### Manually Install ng2-charts with yarn
Source: https://github.com/valor-software/ng2-charts/blob/master/libs/ng2-charts/README.md
Install ng2-charts using yarn. This is an alternative to npm for managing project dependencies.
```bash
yarn add ng2-charts --save
```
--------------------------------
### Manually Install ng2-charts with npm
Source: https://github.com/valor-software/ng2-charts/blob/master/libs/ng2-charts/README.md
Install ng2-charts using npm. This is a manual step before integrating it into your Angular application.
```bash
npm install ng2-charts --save
```
--------------------------------
### Install Chart.js dependency with npm
Source: https://github.com/valor-software/ng2-charts/blob/master/libs/ng2-charts/README.md
Install the Chart.js library, a peer dependency for ng2-charts, using npm. Refer to the official Chart.js documentation for more details.
```bash
npm install chart.js --save
```
--------------------------------
### ProvideCharts: Minimal Registration
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Register only specific Chart.js components for a tree-shaken bundle. This example registers components for a bar chart.
```typescript
// main.ts — minimal registration (tree-shaken bundle)
import { bootstrapApplication } from '@angular/platform-browser';
import { provideCharts } from 'ng2-charts';
import { BarController, CategoryScale, LinearScale, BarElement, Legend, Tooltip } from 'chart.js';
bootstrapApplication(AppComponent, {
providers: [
provideCharts({ registerables: [BarController, CategoryScale, LinearScale, BarElement, Legend, Tooltip] }),
],
});
```
--------------------------------
### Install Chart.js dependency with yarn
Source: https://github.com/valor-software/ng2-charts/blob/master/libs/ng2-charts/README.md
Install the Chart.js library, a peer dependency for ng2-charts, using yarn. This is an alternative to npm.
```bash
yarn add chart.js --save
```
--------------------------------
### Provide Minimal Chart Registrations
Source: https://github.com/valor-software/ng2-charts/blob/master/libs/ng2-charts/README.md
Configure ng2-charts with a minimal set of registerables to reduce bundle size. This example includes only the BarController and Legend.
```typescript
provideCharts({ registerables: [BarController, Legend, Colors] });
```
--------------------------------
### Polar Area Chart Example
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Component for rendering a polar area chart. Requires ChartData and ChartType from 'chart.js'.
```typescript
// polar-area-chart.component.ts
import { Component } from '@angular/core';
import { ChartData, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
@Component({
selector: 'app-polar-area-chart',
standalone: true,
imports: [BaseChartDirective],
template: `
`,
})
export class PolarAreaChartComponent {
public polarAreaChartData: ChartData<'polarArea'> = {
labels: ['Download Sales', 'In-Store Sales', 'Mail Sales', 'Telesales', 'Corporate Sales'],
datasets: [{ data: [300, 500, 100, 40, 120], label: 'Series 1' }],
};
public polarAreaLegend = true;
public polarAreaChartType: ChartType = 'polarArea';
}
```
--------------------------------
### Accessing Chart Instance
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/landing/landing.component.html
How to get access to the chart instance using @ViewChild to call methods like toBase64Image().
```APIDOC
## Chart instance
You can get access to the chart instance by using the `@ViewChild` annotation and a suitable selector for the directive (see the Angular [docs](https://angular.io/api/core/ViewChild)). For example, to get the chart instance and call the `toBase64Image()` method, you can add the following to the parent component:
```typescript
@ViewChild(BaseChartDirective) chart?: BaseChartDirective;
public someAction(): void {
this.chart?.toBase64Image();
}
```
```
--------------------------------
### Scatter Chart Example
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Component for rendering a scatter chart. Data points use { x, y } coordinates. Labels are optional tooltips. Requires ChartData and ChartType from 'chart.js'.
```typescript
// scatter-chart.component.ts
import { Component } from '@angular/core';
import { ChartData, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
@Component({
selector: 'app-scatter-chart',
standalone: true,
imports: [BaseChartDirective],
template: `
`,
})
export class ScatterChartComponent {
public scatterChartData: ChartData<'scatter'> = {
labels: ['Eating', 'Drinking', 'Sleeping', 'Designing', 'Coding', 'Cycling', 'Running'],
datasets: [{
data: [
{ x: 1, y: 1 },
{ x: 2, y: 3 },
{ x: 3, y: -2 },
{ x: 4, y: 4 },
{ x: 5, y: -3 },
],
label: 'Series A',
pointRadius: 10,
}],
};
}
```
--------------------------------
### Access Chart Instance and Use Methods
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/landing/landing.component.html
Get access to the chart instance using @ViewChild to call methods like toBase64Image().
```typescript
@ViewChild(BaseChartDirective) chart?: BaseChartDirective;
public someAction(): void {
this.chart?.toBase64Image();
}
```
--------------------------------
### Bubble Chart Example
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Component for rendering a bubble chart. Data points require { x, y, r } shape, where r is the bubble radius in pixels. Requires ChartData and ChartType from 'chart.js'.
```typescript
// bubble-chart.component.ts
import { Component } from '@angular/core';
import { ChartData, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
@Component({
selector: 'app-bubble-chart',
standalone: true,
imports: [BaseChartDirective],
template: `
`,
})
export class BubbleChartComponent {
public bubbleChartLegend = true;
public bubbleChartOptions = {
scales: {
x: { min: 0, max: 30 },
y: { min: 0, max: 30 },
},
};
public bubbleChartData: ChartData<'bubble'> = {
datasets: [{
data: [
{ x: 10, y: 10, r: 10 }, // r = radius in pixels
{ x: 15, y: 5, r: 15 },
{ x: 26, y: 12, r: 23 },
{ x: 7, y: 8, r: 8 },
],
label: 'Series A',
backgroundColor: ['red', 'green', 'blue', 'purple'],
borderColor: 'blue',
hoverBackgroundColor: 'purple',
hoverBorderColor: 'red',
}],
};
}
```
--------------------------------
### Render a Bar Chart using baseChart Directive
Source: https://github.com/valor-software/ng2-charts/blob/master/libs/ng2-charts/README.md
Use the `baseChart` directive on a canvas element to render different types of charts. This example demonstrates rendering a bar chart by setting the `type` attribute to 'bar'.
```html
```
--------------------------------
### Line Chart with Dual Y-Axes and Annotations in Angular
Source: https://context7.com/valor-software/ng2-charts/llms.txt
This component configures a line chart with two Y-axes, integrates chartjs-plugin-annotation for visual markers, and provides buttons to dynamically update the chart data, visibility, and styling. Ensure 'chart.js' and 'chartjs-plugin-annotation' are installed and imported.
```typescript
// line-chart.component.ts
import { Component, ViewChild } from '@angular/core';
import { ChartConfiguration, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
@Component({
selector: 'app-line-chart',
standalone: true,
imports: [BaseChartDirective],
template: `
`,
})
export class LineChartComponent {
@ViewChild(BaseChartDirective) chart?: BaseChartDirective;
public lineChartData: ChartConfiguration['data'] = {
datasets: [
{
data: [65, 59, 80, 81, 56, 55, 40],
label: 'Series A',
backgroundColor: 'rgba(148,159,177,0.2)',
borderColor: 'rgba(148,159,177,1)',
fill: 'origin',
},
{
data: [28, 48, 40, 19, 86, 27, 90],
label: 'Series B',
backgroundColor: 'rgba(77,83,96,0.2)',
borderColor: 'rgba(77,83,96,1)',
fill: 'origin',
},
{
data: [180, 480, 770, 90, 1000, 270, 400],
label: 'Series C',
yAxisID: 'y1', // bound to right-side axis
backgroundColor: 'rgba(255,0,0,0.3)',
borderColor: 'red',
fill: 'origin',
},
],
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
};
public lineChartOptions: ChartConfiguration['options'] = {
elements: { line: { tension: 0.5 } },
scales: {
y: { position: 'left' },
y1: {
position: 'right',
grid: { color: 'rgba(255,0,0,0.3)' },
ticks: { color: 'red' },
},
},
plugins: {
legend: { display: true },
annotation: {
annotations: [{
type: 'line',
scaleID: 'x',
value: 'March',
borderColor: 'orange',
borderWidth: 2,
label: {
display: true,
position: 'center',
color: 'orange',
content: 'LineAnno',
font: { weight: 'bold' },
},
}],
},
},
};
public lineChartType: ChartType = 'line';
public hideOne(): void {
const isHidden = this.chart?.isDatasetHidden(1);
this.chart?.hideDataset(1, !isHidden); // toggle Series B
}
public pushOne(): void {
this.lineChartData.datasets.forEach((x, i) => {
x.data.push(Math.floor(Math.random() * (i < 2 ? 100 : 1000) + 1));
});
this.lineChartData?.labels?.push(`Label ${this.lineChartData.labels.length}`);
this.chart?.update();
}
public changeColor(): void {
this.lineChartData.datasets[2].borderColor = 'green';
this.lineChartData.datasets[2].backgroundColor = 'rgba(0,255,0,0.3)';
this.chart?.update();
}
public changeLabel(): void {
const tmp = this.lineChartData.datasets[2].label;
this.lineChartData.datasets[2].label = 'Renamed';
this.chart?.update();
}
public chartClicked({ event, active }: { event?: any; active?: object[] }): void {
console.log(event, active);
}
}
```
--------------------------------
### ProvideCharts: With Third-Party Plugins and Global Defaults
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Configure application providers with default Chart.js components, third-party plugins, and global chart defaults.
```typescript
// app.config.ts — with third-party plugins and global defaults
import { provideCharts, withDefaultRegisterables } from 'ng2-charts';
import AnnotationPlugin from 'chartjs-plugin-annotation';
import DataLabelsPlugin from 'chartjs-plugin-datalabels';
import { CandlestickController, CandlestickElement, OhlcController, OhlcElement } from 'chartjs-chart-financial';
export const appConfig: ApplicationConfig = {
providers: [
provideCharts(
withDefaultRegisterables(
CandlestickController, CandlestickElement,
OhlcController, OhlcElement,
DataLabelsPlugin,
AnnotationPlugin,
),
{
defaults: {
font: { family: 'Arial' },
},
},
),
],
};
```
--------------------------------
### Provide Minimal Chart Configuration
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/landing/landing.component.html
Provide a minimal configuration to reduce bundle size by specifying only necessary registerables.
```typescript
provideCharts({
registerables: [BarController, Legend, Colors]
})
```
--------------------------------
### provideCharts
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Registers Chart.js components and sets global defaults. Must be called once at application bootstrap.
```APIDOC
## provideCharts
`provideCharts(...configurations: NgChartsConfiguration[])` registers Chart.js components (controllers, scales, elements, plugins) and sets global Chart.js defaults at the application level. It must be called once in `bootstrapApplication` or an `NgModule` providers array. Multiple configuration objects are deep-merged.
### Usage Examples:
```typescript
// main.ts — full registration (largest bundle)
import { bootstrapApplication } from '@angular/platform-browser';
import { provideCharts, withDefaultRegisterables } from 'ng2-charts';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, {
providers: [
provideCharts(withDefaultRegisterables()),
],
});
// main.ts — minimal registration (tree-shaken bundle)
import { bootstrapApplication } from '@angular/platform-browser';
import { provideCharts } from 'ng2-charts';
import { BarController, CategoryScale, LinearScale, BarElement, Legend, Tooltip } from 'chart.js';
bootstrapApplication(AppComponent, {
providers: [
provideCharts({ registerables: [BarController, CategoryScale, LinearScale, BarElement, Legend, Tooltip] }),
],
});
// app.config.ts — with third-party plugins and global defaults
import { provideCharts, withDefaultRegisterables } from 'ng2-charts';
import AnnotationPlugin from 'chartjs-plugin-annotation';
import DataLabelsPlugin from 'chartjs-plugin-datalabels';
import { CandlestickController, CandlestickElement, OhlcController, OhlcElement } from 'chartjs-chart-financial';
export const appConfig: ApplicationConfig = {
providers: [
provideCharts(
withDefaultRegisterables(
CandlestickController, CandlestickElement,
OhlcController, OhlcElement,
DataLabelsPlugin,
AnnotationPlugin,
),
{
defaults: {
font: { family: 'Arial' },
},
},
),
],
};
```
```
--------------------------------
### ProvideCharts: Full Registration
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Register all Chart.js components and defaults at application bootstrap for the largest bundle size.
```typescript
// main.ts — full registration (largest bundle)
import { bootstrapApplication } from '@angular/platform-browser';
import { provideCharts, withDefaultRegisterables } from 'ng2-charts';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, {
providers: [
provideCharts(withDefaultRegisterables()),
],
});
```
--------------------------------
### Dynamic Theming with ThemeService
Source: https://github.com/valor-software/ng2-charts/blob/master/README.md
Implement dynamic theming for charts using `ThemeService`. This allows overriding chart options, including colors, based on the selected theme. The `overrides` object structure mirrors `ChartOptions`, with special handling for arrays.
```typescript
type Theme = 'light-theme' | 'dark-theme';
private _selectedTheme: Theme = 'light-theme';
public get selectedTheme(){
return this._selectedTheme;
}
public set selectedTheme(value){
this._selectedTheme = value;
let overrides: ChartOptions;
if (this.selectedTheme === 'dark-theme') {
overrides = {
legend: {
labels: { fontColor: 'white' }
},
scales: {
xAxes: [ {
ticks: { fontColor: 'white' },
gridLines: { color: 'rgba(255,255,255,0.1)' }
} ],
yAxes: [ {
ticks: { fontColor: 'white' },
gridLines: { color: 'rgba(255,255,255,0.1)' }
} ]
}
};
} else {
overrides = {};
}
this.themeService.setColorschemesOptions(overrides);
}
constructor(private themeService: ThemeService){
}
setCurrentTheme(theme: Theme){
this.selectedTheme = theme;
}
```
--------------------------------
### Runtime Dynamic Theming with ThemeService
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Component demonstrating runtime dynamic theming. Provided in root, ThemeService allows globally overriding Chart.js color options at runtime.
```typescript
// theme-switcher.component.ts
import { Component, inject } from '@angular/core';
import { ThemeService } from 'ng2-charts';
import { ChartOptions } from 'chart.js';
type AppTheme = 'light-theme' | 'dark-theme';
@Component({
selector: 'app-theme-switcher',
standalone: true,
template: `
`,
})
export class ThemeSwitcherComponent {
private themeService = inject(ThemeService);
setTheme(theme: AppTheme): void {
let overrides: ChartOptions = {};
if (theme === 'dark-theme') {
overrides = {
plugins: { legend: { labels: { color: 'white' } } },
scales: {
x: {
ticks: { color: 'white' },
grid: { color: 'rgba(255,255,255,0.1)' },
},
y: {
ticks: { color: 'white' },
grid: { color: 'rgba(255,255,255,0.1)' },
},
},
};
}
// Pushes options to all active BaseChartDirective instances via BehaviorSubject
this.themeService.setColorschemesOptions(overrides);
}
getCurrentThemeOptions(): ChartOptions | undefined {
return this.themeService.getColorschemesOptions();
}
}
```
--------------------------------
### Dynamic Theming with ThemeService
Source: https://github.com/valor-software/ng2-charts/blob/master/libs/ng2-charts/README.md
Demonstrates how to use ThemeService to dynamically override chart options, such as legend and axis colors, based on a selected theme. This is useful for adapting chart appearance to different application themes like light or dark mode.
```typescript
type Theme = 'light-theme' | 'dark-theme';
private _selectedTheme: Theme = 'light-theme';
public get selectedTheme(){
return this._selectedTheme;
}
public set selectedTheme(value){
this._selectedTheme = value;
let overrides: ChartOptions;
if (this.selectedTheme === 'dark-theme') {
overrides = {
legend: {
labels: { fontColor: 'white' }
},
scales: {
xAxes: [ {
ticks: { fontColor: 'white' },
gridLines: { color: 'rgba(255,255,255,0.1)' }
} ],
yAxes: [ {
ticks: { fontColor: 'white' },
gridLines: { color: 'rgba(255,255,255,0.1)' }
} ]
}
};
} else {
overrides = {};
}
this.themeService.setColorschemesOptions(overrides);
}
constructor(private themeService: ThemeService){
}
setCurrentTheme(theme: Theme){
this.selectedTheme = theme;
}
```
--------------------------------
### Provide Global Chart Configuration
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/landing/landing.component.html
Configure charts globally by providing default registerables in your application's configuration.
```typescript
import { provideCharts, withDefaultRegisterables } from 'ng2-charts';
bootstrapApplication(AppComponent, {
providers: [
provideCharts(withDefaultRegisterables()),
],
}).catch((err) => console.error(err));
```
--------------------------------
### Dynamic Theming
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/landing/landing.component.html
Using the ThemeService to dynamically override chart colors and options.
```APIDOC
## Dynamic Theming
The `ThemeService` allows clients to set a structure specifying colors override settings. This service may be called when the dynamic theme changes, with colors which fit the theme. The structure is interpreted as an override, so in order to reset any existing option or customization you will have to define `undefined` properties explicitly. For example:
```typescript
type Theme = 'light-theme' | 'dark-theme';
private _selectedTheme: Theme = 'light-theme';
public get selectedTheme() {
return this._selectedTheme;
}
public set selectedTheme(value) {
this._selectedTheme = value;
let overrides: ChartOptions;
if (this.selectedTheme === 'dark-theme') {
overrides = {
scales: {
x: [{ ticks: { fontColor: 'white' }, gridLines: { color: 'rgba(255,255,255,0.1)' } }],
y: [{ ticks: { fontColor: 'white' }, gridLines: { color: 'rgba(255,255,255,0.1)' } }]
}
};
} else {
overrides = {
scales: undefined
};
}
this.themeService.setColorschemesOptions(overrides);
}
constructor(private themeService: ThemeService) {}
setCurrentTheme(theme: Theme) {
this.selectedTheme = theme;
}
```
The `overrides` object has the same type as the chart options object `ChartOptions`, and wherever a simple field is encountered it replaces the matching field in the `options` object. When an array is encountered (as in the `xAxes` and `yAxes` fields above), the single object inside the array is used as a template to override all array elements in the matching field in the `options` object. So in the case above, every axis will have its ticks and gridline colors changed.
```
--------------------------------
### Radar Chart Implementation
Source: https://context7.com/valor-software/ng2-charts/llms.txt
A basic radar chart implementation. Ensure Chart.js and ng2-charts are properly imported and configured.
```typescript
// radar-chart.component.ts
import { Component } from '@angular/core';
import { ChartData, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
@Component({
selector: 'app-radar-chart',
standalone: true,
imports: [BaseChartDirective],
template: `
`,
})
export class RadarChartComponent {
public radarChartOptions = {};
public radarChartData: ChartData<'radar'> = {
labels: ['Eating', 'Drinking', 'Sleeping', 'Designing', 'Coding', 'Cycling', 'Running'],
datasets: [
{ data: [65, 59, 90, 81, 56, 55, 40], label: 'Series A' },
{ data: [28, 48, 40, 19, 96, 27, 100], label: 'Series B' },
],
};
}
```
--------------------------------
### Pie Chart with Dynamic Slices and Legend Controls
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Implement a pie chart with multi-line labels, dynamic slice addition/removal, and legend position/visibility toggling. Use `chart.render()` when options structure changes.
```typescript
// pie-chart.component.ts
import { Component, ViewChild } from '@angular/core';
import { ChartData, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
@Component({
selector: 'app-pie-chart',
standalone: true,
imports: [BaseChartDirective],
template: `
`,
})
export class PieChartComponent {
@ViewChild(BaseChartDirective) chart: BaseChartDirective | undefined;
public pieChartOptions = {
plugins: {
legend: { display: true, position: 'top' as const },
datalabels: {
formatter: (value: number, ctx: any) =>
ctx.chart.data.labels ? ctx.chart.data.labels[ctx.dataIndex] : '',
},
},
};
// Labels can be arrays for multi-line display
public pieChartData: ChartData<'pie', number[], string | string[]> = {
labels: [['Download', 'Sales'], ['In', 'Store', 'Sales'], 'Mail Sales'],
datasets: [{ data: [300, 500, 100] }],
};
public pieChartType: ChartType = 'pie';
addSlice(): void {
this.pieChartData.labels?.push(['Line 1', 'Line 2', 'Line 3']);
this.pieChartData.datasets[0].data.push(400);
this.chart?.update();
}
removeSlice(): void {
this.pieChartData.labels?.pop();
this.pieChartData.datasets[0].data.pop();
this.chart?.update();
}
changeLegendPosition(): void {
if (this.pieChartOptions?.plugins?.legend) {
this.pieChartOptions.plugins.legend.position =
this.pieChartOptions.plugins.legend.position === 'left' ? 'top' : 'left';
}
this.chart?.render(); // render() needed when options structure changes
}
toggleLegend(): void {
if (this.pieChartOptions?.plugins?.legend) {
this.pieChartOptions.plugins.legend.display =
!this.pieChartOptions.plugins.legend.display;
}
this.chart?.render();
}
chartClicked({ event, active }: { event: any; active: object[] }): void {
console.log(event, active);
}
}
```
--------------------------------
### Dynamic Theming with ThemeService
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/landing/landing.component.html
Use ThemeService to dynamically override chart colors and options based on themes.
```typescript
type Theme = 'light-theme' | 'dark-theme';
private _selectedTheme: Theme = 'light-theme';
public get selectedTheme() {
return this._selectedTheme;
}
public set selectedTheme(value) {
this._selectedTheme = value;
let overrides: ChartOptions;
if (this.selectedTheme === 'dark-theme') {
overrides = {
scales: {
x: [{ ticks: { fontColor: 'white' }, gridLines: { color: 'rgba(255,255,255,0.1)' } }],
y: [{ ticks: { fontColor: 'white' }, gridLines: { color: 'rgba(255,255,255,0.1)' } }]
}
};
} else {
overrides = {
scales: undefined
};
}
this.themeService.setColorschemesOptions(overrides);
}
constructor(private themeService: ThemeService) {}
setCurrentTheme(theme: Theme) {
this.selectedTheme = theme;
}
```
--------------------------------
### Dynamic Chart Type Switching
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Demonstrates switching between 'bar' and 'line' chart types at runtime by changing the 'type' input. This triggers a full chart re-render. Requires ChartData and ChartType from 'chart.js'.
```typescript
// dynamic-chart.component.ts
import { Component, ViewChild } from '@angular/core';
import { ChartData, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
@Component({
selector: 'app-dynamic-chart',
standalone: true,
imports: [BaseChartDirective],
template: `
`,
})
export class DynamicChartComponent {
@ViewChild(BaseChartDirective) chart: BaseChartDirective | undefined;
public chartType: ChartType = 'bar';
public chartOptions = {
elements: { line: { tension: 0.4 } },
scales: { x: {}, y: { min: 10 } },
plugins: { legend: { display: true } },
};
public chartData: ChartData<'bar'> = {
labels: ['2006', '2007', '2008', '2009', '2010', '2011', '2012'],
datasets: [
{ data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' },
{ data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B' },
],
};
public toggleType(): void {
// Assigning a new type value triggers ngOnChanges → render()
this.chartType = this.chartType === 'bar' ? 'line' : 'bar';
}
}
```
--------------------------------
### NgChartsConfiguration and withDefaultRegisterables
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Demonstrates how to define NgChartsConfiguration and use withDefaultRegisterables to pre-populate it with Chart.js built-ins and custom plugins. This is useful for setting up chart defaults and registering custom components.
```typescript
import { provideCharts, withDefaultRegisterables } from 'ng2-charts';
import type { NgChartsConfiguration } from 'ng2-charts';
import { Tooltip, Legend } from 'chart.js';
import MyCustomPlugin from './my-custom-plugin';
// Type reference
const config: NgChartsConfiguration = {
registerables: [Tooltip, Legend, MyCustomPlugin],
defaults: {
color: '#333',
font: { size: 14, family: 'Inter' },
},
};
// Use withDefaultRegisterables to extend all built-ins + custom additions
const provider = provideCharts(
withDefaultRegisterables(MyCustomPlugin),
{ defaults: { color: '#333' } },
);
// → registers all Chart.js built-ins + MyCustomPlugin, sets default color
// Typical NgModule usage
@NgModule({
providers: [provideCharts(withDefaultRegisterables())],
bootstrap: [AppComponent],
})
export class AppModule {}
```
--------------------------------
### Doughnut Chart with Multiple Datasets
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Create a doughnut chart that displays multiple concentric ring datasets. Each dataset is rendered as an independent ring.
```typescript
// doughnut-chart.component.ts
import { Component } from '@angular/core';
import { ChartData, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
@Component({
selector: 'app-doughnut-chart',
standalone: true,
imports: [BaseChartDirective],
template: `
`,
})
export class DoughnutChartComponent {
public doughnutChartData: ChartData<'doughnut'> = {
labels: ['Download Sales', 'In-Store Sales', 'Mail-Order Sales'],
datasets: [
{ data: [350, 450, 100] }, // outer ring
{ data: [50, 150, 120] }, // middle ring
{ data: [250, 130, 70] }, // inner ring
],
};
public doughnutChartType: ChartType = 'doughnut';
chartClicked({ event, active }: { event: any; active: object[] }): void {
console.log(event, active);
}
}
```
--------------------------------
### Provide Default Chart Registrations in main.ts
Source: https://github.com/valor-software/ng2-charts/blob/master/libs/ng2-charts/README.md
Configure ng2-charts by providing default chart controllers and plugins in your application's main entry point (`main.ts`). This ensures all chart types are available.
```typescript
import { provideCharts, withDefaultRegisterables } from 'ng2-charts';
bootstrapApplication(AppComponent, {
providers: [provideCharts(withDefaultRegisterables())],
}).catch((err) => console.error(err));
```
--------------------------------
### render
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Destroys and re-creates the Chart.js instance from current inputs. This is useful for a full refresh of the chart.
```APIDOC
## render
### Description
Destroys and re-creates the Chart.js instance from current inputs.
### Signature
`render(): Chart | undefined`
```
--------------------------------
### Global Configuration
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/landing/landing.component.html
Provide global configuration for ng2-charts in your app.config.ts or equivalent.
```APIDOC
## Global configuration
You also need to provide a global configuration in your `app.config.ts` (or wherever that makes sense if you are lazy-loading things):
```typescript
import { provideCharts, withDefaultRegisterables } from 'ng2-charts';
bootstrapApplication(AppComponent, {
providers: [
provideCharts(withDefaultRegisterables()),
],
}).catch((err) => console.error(err));
```
Alternatively, include a minimal configuration to reduce the bundle size, eg:
```typescript
provideCharts({
registerables: [BarController, Legend, Colors]
})
```
```
--------------------------------
### Provide Default Chart Registrations in AppModule
Source: https://github.com/valor-software/ng2-charts/blob/master/libs/ng2-charts/README.md
Configure ng2-charts by providing default chart controllers and plugins within your application's root `AppModule`. This is an alternative to configuring in `main.ts`.
```typescript
import { provideCharts, withDefaultRegisterables } from 'ng2-charts';
@NgModule({
providers: [provideCharts(withDefaultRegisterables())],
bootstrap: [AppComponent],
})
export class AppModule {}
```
--------------------------------
### Displaying Chart Data Point
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/line-chart/line-chart.component.html
Renders a specific data point for a chart dataset. Ensures the dataset and data exist before rendering.
```html
{{ d && d.data[j] }}
```
--------------------------------
### Chart Properties
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/landing/landing.component.html
Properties available for the `baseChart` directive to configure chart data and appearance.
```APIDOC
## Properties
**Note**: For more information about possible options please refer to original [chart.js](http://www.chartjs.org/docs) documentation
- `data` - set of points of the chart. See https://www.chartjs.org/docs/latest/general/data-structures.html for some examples and further reference. Use this property or `datasets`/`labels` depending on what's convenient.
- `datasets` - Same as the `datasets` property for the `data` input. `data` Has priority over this.
- `labels` - Same as the `labels` property for the `data` input. `data` has priority over this.
- `type` (`ChartType`) - indicates the type of charts. Defaults to `bar`.
- `options` (`ChartOptions`) - chart options (as from [Chart.js documentation](http://www.chartjs.org/docs/))
- `legend`: (`boolean = false`) - if true show legend below the chart, otherwise not be shown
```
--------------------------------
### Displaying Chart Label
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/line-chart/line-chart.component.html
Renders a single chart label within an Angular template. Assumes 'label' is defined in the scope.
```html
{{ label }}
```
--------------------------------
### toBase64Image
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Exports the chart canvas as a base64 PNG data URL. This is useful for saving or sharing the chart as an image.
```APIDOC
## toBase64Image
### Description
Exports the chart canvas as a base64 PNG data URL.
### Signature
`toBase64Image(): string | undefined`
```
--------------------------------
### Import BaseChartDirective in Standalone Component
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/landing/landing.component.html
Import the BaseChartDirective into your standalone component to use charts.
```typescript
import { BaseChartDirective } from 'ng2-charts';
@Component({
standalone: true,
imports: [BaseChartDirective],
})
export class MyComponent {}
```
--------------------------------
### Chart Interaction Buttons
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/line-chart/line-chart.component.html
Provides buttons to interact with the chart, such as randomizing data, pushing new data, recoloring, and toggling series visibility.
```html
Randomize Push Recolor Toggle Series B Change Label
```
--------------------------------
### Usage in Standalone Component
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/landing/landing.component.html
Import the BaseChartDirective into your standalone component to use ng2-charts.
```APIDOC
## Usage
In order to use ***ng2-charts*** you need to import the directive in your standalone component:
```typescript
import { BaseChartDirective } from 'ng2-charts';
@Component({
standalone: true,
imports: [BaseChartDirective],
})
export class MyComponent {
// Component logic here
}
```
```
--------------------------------
### Line Chart Data Iteration
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/line-chart/line-chart.component.html
Iterates over chart labels and datasets to render data points. Used within an Angular template.
```html
@for (label of lineChartData.labels; track label) { }
@for (d of lineChartData.datasets; track d; let i = $index) { }
@for (label of lineChartData.labels; track label; let j = $index) { }
```
--------------------------------
### update
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Calls `chart.update()`. Use this method after mutating `data` or `options` directly to reflect changes in the chart.
```APIDOC
## update
### Description
Calls `chart.update()`. Use after mutating `data` or `options` directly.
### Signature
`update(mode?: UpdateMode): void`
```
--------------------------------
### Financial Candlestick/OHLC Chart Component
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Component for rendering financial charts. Requires 'chartjs-chart-financial' and 'chartjs-adapter-date-fns'. The custom controllers and elements must be registered.
```typescript
// financial-chart.component.ts
import { Component, ViewChild } from '@angular/core';
import 'chartjs-adapter-date-fns';
import { BaseChartDirective } from 'ng2-charts';
import { ChartConfiguration, ChartType } from 'chart.js';
import { enUS } from 'date-fns/locale';
import { add, parseISO } from 'date-fns';
@Component({
selector: 'app-financial-chart',
standalone: true,
imports: [BaseChartDirective],
template: `
`,
})
export class FinancialChartComponent {
@ViewChild(BaseChartDirective) chart?: BaseChartDirective;
public financialChartType: ChartType = 'candlestick';
public financialChartData: ChartConfiguration['data'] = {
datasets: [{
label: 'CHRT - Chart.js Corporation',
data: this.getRandomData('2017-04-01T00:00:00', 60),
}],
};
public financialChartOptions: ChartConfiguration['options'] = {
animation: false,
scales: {
x: {
time: { unit: 'day' },
adapters: { date: { locale: enUS } },
ticks: { source: 'auto' },
},
},
plugins: {
datalabels: { display: false },
legend: { display: false },
},
};
getRandomData(dateStr: string, count: number): { x: number; o: number; h: number; l: number; c: number }[] {
let date = parseISO(dateStr);
const randomBar = (d: Date, lastClose: number) => {
const open = lastClose * (0.95 + Math.random() * 0.1);
const close = open * (0.95 + Math.random() * 0.1);
const high = Math.max(open, close) * (1 + Math.random() * 0.1);
const low = Math.min(open, close) * (0.9 + Math.random() * 0.1);
return { x: +d, o: open, h: high, l: low, c: close };
};
const data = [randomBar(date, 30)];
while (data.length < count) {
date = add(date, { days: 1 });
if (date.getDay() <= 5) data.push(randomBar(date, data[data.length - 1].c));
}
return data;
}
toggleType(): void {
this.financialChartType = this.financialChartType === 'candlestick' ? 'ohlc' : 'candlestick';
}
randomize(): void {
this.financialChartData.datasets = [{
label: 'CHRT - Chart.js Corporation',
data: this.getRandomData('2017-04-01T00:00:00', 60),
}];
this.chart?.update();
}
}
```
--------------------------------
### hideDataset
Source: https://context7.com/valor-software/ng2-charts/llms.txt
Shows or hides a dataset by its index. This allows for dynamic control over dataset visibility.
```APIDOC
## hideDataset
### Description
Shows or hides a dataset by index.
### Signature
`hideDataset(index: number, hidden: boolean): void`
```
--------------------------------
### Chart Events
Source: https://github.com/valor-software/ng2-charts/blob/master/apps/ng2-charts-demo/src/app/landing/landing.component.html
Events emitted by the chart directive for user interactions.
```APIDOC
## Events
- `chartClick`: fires when click on a chart has occurred, returns information regarding active points and labels
- `chartHover`: fires when mousemove (hover) on a chart has occurred, returns information regarding active points and labels
```