方法来源
https://www.npmjs.com/package/angular-highcharts
第一步
安装模块angular-highcharts 和 highcharts模块
// install angular-highcharts and highcharts
npm i --save angular-highcharts highcharts
第二步
在模块中引入
// app.module.ts
import { ChartModule } from 'angular-highcharts';
@NgModule({
imports: [
ChartModule // add ChartModule to your imports
]
})
export class AppModule {}
第三步
配置及实例使用
// chart.component.ts
import { Chart } from 'angular-highcharts';
@Component({
template: `
<button (click)="add()">Add Point!</button>
<div [chart]="chart"></div>
`
})
export class ChartComponent {
chart = new Chart({
chart: {
type: 'line'
},
title: {
text: 'Linechart'
},
credits: {
enabled: false
},
series: [
{
name: 'Line 1',
data: [1, 2, 3]
}
]
});
// add point to chart serie
add() {
this.chart.addPoint(Math.floor(Math.random() * 10));
}
}
最佳实践
//app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ChartModule } from 'angular-highcharts';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule, ChartModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
//app.comp//apponent.ts
import { Component } from '@angular/core';
import { Chart } from 'angular-highcharts';
@Component({
selector: 'my-app',
templateUrl: './app.component.html'
})
export class AppComponent {
chart: Chart;
ngOnInit() {
this.init();
}
addPoint() {
if (this.chart) {
this.chart.addPoint(Math.floor(Math.random() * 10));
} else {
alert('init chart, first!');
}
}
addSerie() {
this.chart.addSeries({
name: 'Line ' + Math.floor(Math.random() * 10),
data: [
Math.floor(Math.random() * 10),
Math.floor(Math.random() * 10),
Math.floor(Math.random() * 10),
Math.floor(Math.random() * 10),
Math.floor(Math.random() * 10),
Math.floor(Math.random() * 10),
Math.floor(Math.random() * 10),
Math.floor(Math.random() * 10),
Math.floor(Math.random() * 10)
]
});
}
removePoint() {
this.chart.removePoint(this.chart.ref.series[0].data.length - 1);
}
removeSerie() {
this.chart.removeSeries(this.chart.ref.series.length - 1);
}
init() {
let chart = new Chart({
chart: {
type: 'line'
},
title: {
text: 'Linechart'
},
credits: {
enabled: false
},
series: [{
name: 'Line 1',
data: [1, 2, 3]
}]
});
chart.addPoint(4);
this.chart = chart;
chart.addPoint(5);
setTimeout(() => {
chart.addPoint(6);
}, 2000);
chart.ref$.subscribe(console.log);
}
}
// app.component.html
<button (click)="init()">Init</button>
<button (click)="addSerie()">Add Serie</button>
<button (click)="removeSerie()">Remove Serie</button>
<button (click)="addPoint()">Add Point</button>
<button (click)="removePoint()">Remove Point</button>
<div [chart]="chart"></div>