M. Rogers
M. Rogers

Reputation: 47

Chart.js and Angular - Click Event on Chart

I am using Chart.js to create a line graph for some data. I want to be able to select a point on the graph and then below load more data that is associated with that data point. I am a bit stuck on how to do this.

In profile.component.html I have

<canvas [lineGraph]="graphData" width="700" height="400"></canvas>

In graph.directive.ts (some code cut to make it short) I have

@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
        });    
    }
}

I also have a profile.component.ts file but I am omitting all code for now as it doesn't seem important right now.

What I have tried

I tried putting

canvas.onclick = function (event) {
    ... code to get the point clicked on such as 
    this.myChart.getPointsAtEvent( event )
};

in graph.directive.ts but myChart is null then. I was placing that in generateLineGraph() as that seemed the only place I could put it.

I tried putting (click)="chartClick($event)" into profile.component.html so it would be

   <canvas [lineGraph]="graphData" width="700" height="400" (click)="chartClick($event)"></canvas>

and then a chartClick function in profile.component.ts but then I don't know how to get a reference to the chart in graph.directive.ts.

What would be the best approach to solve this problem?

Upvotes: 1

Views: 7491

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658017

Use ()=> instead of function() to keep the scope of this within the callback:

canvas.onclick = (event) => {
    ... code to get the point clicked on such as 
    this.myChart.getPointsAtEvent( event )
};

For more details see https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Upvotes: 2

Related Questions