or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

chart-directive.mdconfiguration.mdindex.mdtheming.md

chart-directive.mddocs/

0

# Chart Directive

1

2

The BaseChartDirective is the core component of ng2-charts that provides Angular integration for Chart.js. It supports 8 chart types with reactive data binding, event handling, and lifecycle management.

3

4

## Capabilities

5

6

### BaseChartDirective

7

8

Angular directive that wraps Chart.js functionality with full TypeScript support and Angular lifecycle integration.

9

10

```typescript { .api }

11

/**

12

* Angular directive for creating reactive charts using Chart.js

13

* Supports all Chart.js chart types with Angular data binding and events

14

*/

15

@Directive({

16

selector: 'canvas[baseChart]',

17

exportAs: 'base-chart',

18

standalone: true

19

})

20

export class BaseChartDirective<

21

TType extends ChartType = ChartType,

22

TData = DefaultDataPoint<TType>,

23

TLabel = unknown

24

> implements OnDestroy, OnChanges {

25

26

/** Chart type: 'line', 'bar', 'radar', 'pie', 'polarArea', 'doughnut', 'bubble', 'scatter' */

27

@Input() type: ChartConfiguration<TType, TData, TLabel>['type'];

28

29

/** Show/hide chart legend */

30

@Input() legend?: boolean;

31

32

/** Complete chart data structure (alternative to labels/datasets) */

33

@Input() data?: ChartConfiguration<TType, TData, TLabel>['data'];

34

35

/** Chart configuration options */

36

@Input() options: ChartConfiguration<TType, TData, TLabel>['options'];

37

38

/** Array of Chart.js plugins */

39

@Input() plugins: Plugin<TType>[];

40

41

/** Chart labels (used with datasets input) */

42

@Input() labels?: ChartConfiguration<TType, TData, TLabel>['data']['labels'];

43

44

/** Chart datasets (used with labels input) */

45

@Input() datasets?: ChartConfiguration<TType, TData, TLabel>['data']['datasets'];

46

47

/** Emits when chart is clicked */

48

@Output() chartClick: EventEmitter<{event?: ChartEvent; active?: object[]}>;

49

50

/** Emits when chart is hovered */

51

@Output() chartHover: EventEmitter<{event: ChartEvent; active: object[]}>;

52

53

/** Canvas 2D context */

54

ctx: string;

55

56

/** Chart.js instance */

57

chart?: Chart<TType, TData, TLabel>;

58

59

/**

60

* Constructor for BaseChartDirective

61

* @param element - ElementRef to the canvas element

62

* @param zone - NgZone for running outside Angular zone for performance

63

* @param themeService - ThemeService for dynamic theming

64

* @param config - Optional ng2-charts configuration

65

*/

66

constructor(element: ElementRef, zone: NgZone, themeService: ThemeService, config?: NgChartsConfiguration);

67

68

/** Lifecycle method called when input properties change */

69

ngOnChanges(changes: SimpleChanges): void;

70

71

/** Lifecycle method called when component is destroyed */

72

ngOnDestroy(): void;

73

}

74

```

75

76

**Usage Examples:**

77

78

```typescript

79

import { Component } from '@angular/core';

80

import { BaseChartDirective } from 'ng2-charts';

81

import { ChartData, ChartOptions, ChartType } from 'chart.js';

82

83

@Component({

84

template: `

85

<canvas

86

baseChart

87

[data]="lineChartData"

88

[options]="lineChartOptions"

89

[type]="'line'"

90

(chartClick)="onChartClick($event)">

91

</canvas>

92

`,

93

standalone: true,

94

imports: [BaseChartDirective]

95

})

96

export class LineChartComponent {

97

lineChartData: ChartData<'line'> = {

98

labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],

99

datasets: [{

100

data: [65, 59, 80, 81, 56, 55, 40],

101

label: 'Series A',

102

fill: false,

103

tension: 0.5,

104

borderColor: 'rgb(75, 192, 192)',

105

backgroundColor: 'rgba(75, 192, 192, 0.2)'

106

}]

107

};

108

109

lineChartOptions: ChartOptions<'line'> = {

110

responsive: false

111

};

112

113

onChartClick(event: any) {

114

console.log(event);

115

}

116

}

117

```

118

119

### Chart Rendering

120

121

Creates or recreates the Chart.js instance.

122

123

```typescript { .api }

124

/**

125

* Creates or recreates the Chart.js instance

126

* Destroys existing chart if present and creates a new one

127

* @returns The created Chart.js instance

128

*/

129

render(): Chart<TType, TData, TLabel>;

130

```

131

132

### Chart Updates

133

134

Updates the chart with current data without full recreation.

135

136

```typescript { .api }

137

/**

138

* Updates the chart with current data

139

* More efficient than render() for data changes

140

* @param mode - Chart.js update mode ('resize', 'reset', 'none', 'hide', 'show', 'normal', 'active')

141

*/

142

update(mode?: UpdateMode): void;

143

```

144

145

### Dataset Visibility

146

147

Controls visibility of individual datasets within the chart.

148

149

```typescript { .api }

150

/**

151

* Shows or hides a specific dataset

152

* @param index - Dataset index

153

* @param hidden - Whether to hide the dataset

154

*/

155

hideDataset(index: number, hidden: boolean): void;

156

157

/**

158

* Checks if a dataset is currently hidden

159

* @param index - Dataset index

160

* @returns True if hidden, false if visible, undefined if dataset doesn't exist

161

*/

162

isDatasetHidden(index: number): boolean | undefined;

163

```

164

165

### Chart Export

166

167

Exports the chart as a base64-encoded image.

168

169

```typescript { .api }

170

/**

171

* Returns the chart as a base64-encoded PNG image

172

* @returns Base64 image string or undefined if chart not available

173

*/

174

toBase64Image(): string | undefined;

175

```

176

177

**Usage Example:**

178

179

```typescript

180

import { Component, ViewChild } from '@angular/core';

181

import { BaseChartDirective } from 'ng2-charts';

182

import { ChartData } from 'chart.js';

183

184

@Component({

185

template: `

186

<canvas #chart baseChart [data]="chartData" [type]="'bar'"></canvas>

187

<button (click)="exportChart()">Export Chart</button>

188

<button (click)="toggleDataset(0)">Toggle First Dataset</button>

189

`,

190

standalone: true,

191

imports: [BaseChartDirective]

192

})

193

export class ChartControlComponent {

194

@ViewChild('chart') chart!: BaseChartDirective;

195

196

chartData = {

197

labels: ['Red', 'Blue', 'Yellow'],

198

datasets: [{

199

label: 'Dataset 1',

200

data: [300, 50, 100]

201

}, {

202

label: 'Dataset 2',

203

data: [50, 250, 120]

204

}]

205

};

206

207

exportChart() {

208

const base64 = this.chart.toBase64Image();

209

if (base64) {

210

const link = document.createElement('a');

211

link.download = 'chart.png';

212

link.href = base64;

213

link.click();

214

}

215

}

216

217

toggleDataset(index: number) {

218

const isHidden = this.chart.isDatasetHidden(index);

219

this.chart.hideDataset(index, !isHidden);

220

}

221

}

222

```

223

224

## Supported Chart Types

225

226

ng2-charts supports all standard Chart.js chart types:

227

228

- **line**: Line charts for showing trends over time

229

- **bar**: Bar charts for comparing categorical data

230

- **radar**: Radar charts for showing multivariate data

231

- **pie**: Pie charts for showing proportional data

232

- **polarArea**: Polar area charts for circular data representation

233

- **doughnut**: Doughnut charts (pie charts with hollow center)

234

- **bubble**: Bubble charts for three-dimensional data

235

- **scatter**: Scatter plots for showing correlation between variables

236

237

## Event Handling

238

239

### Chart Click Events

240

241

```typescript { .api }

242

interface ChartClickEvent {

243

event?: ChartEvent;

244

active?: object[];

245

}

246

```

247

248

### Chart Hover Events

249

250

```typescript { .api }

251

interface ChartHoverEvent {

252

event: ChartEvent;

253

active: object[];

254

}

255

```

256

257

**Event Usage Example:**

258

259

```typescript

260

import { Component } from '@angular/core';

261

import { BaseChartDirective } from 'ng2-charts';

262

import { ChartEvent } from 'chart.js';

263

264

@Component({

265

template: `

266

<canvas

267

baseChart

268

[data]="chartData"

269

[type]="'bar'"

270

(chartClick)="onChartClick($event)"

271

(chartHover)="onChartHover($event)">

272

</canvas>

273

`,

274

standalone: true,

275

imports: [BaseChartDirective]

276

})

277

export class InteractiveChartComponent {

278

onChartClick(event: {event?: ChartEvent; active?: object[]}) {

279

if (event.active && event.active.length > 0) {

280

console.log('Clicked on data point:', event.active);

281

}

282

}

283

284

onChartHover(event: {event: ChartEvent; active: object[]}) {

285

if (event.active.length > 0) {

286

console.log('Hovering over data point:', event.active);

287

}

288

}

289

}

290

```