我正在使用Chart.js爲某些數據創建線圖。我希望能夠選擇圖上的一個點,然後加載更多與該數據點關聯的數據。我有點卡住如何做到這一點。Chart.js和Angular - 在圖上單擊事件
在profile.component.html我
<canvas [lineGraph]="graphData" width="700" height="400"></canvas>
在graph.directive.ts(一些代碼切割,使之短)我有
@Directive({
selector: '[lineGraph]'
})
export class LineGraphDirective {
@Input('lineGraph') data:any;
el:any;
myChart:any;
constructor(element:ElementRef) {
this.el = element.nativeElement;
}
ngAfterViewInit() {
this.generateLineGraph();
}
private generateLineGraph() {
var canvas = this.el;
var _data = {...load data here from data input};
var _options = {...get options here};
this.myChart = new Chart(canvas.getContext('2d'), {
type: 'line',
data: _data,
options: _options
});
}
}
我也有一個profile.component .ts文件,但我現在省略了所有的代碼,因爲它現在看起來並不重要。
我已經試過
我試圖把
canvas.onclick = function (event) {
... code to get the point clicked on such as
this.myChart.getPointsAtEvent(event)
};
在graph.directive.ts但myChart爲空即可。我把它放在generateLineGraph()中,因爲這似乎是我可以放置它的唯一地方。
我試圖把 (點擊)= 「chartClick($事件)」 到profile.component.html所以這將是
<canvas [lineGraph]="graphData" width="700" height="400" (click)="chartClick($event)"></canvas>
,然後在profile.component.ts一個chartClick功能,但隨後我不知道如何在graph.directive.ts中獲得對圖表的引用。
什麼是解決此問題的最佳方法?