1

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.