Reputation: 2203
I'm using Chart.js
with a plugin to drag data points. The chart needs a options
object to be passed to customize it and triggers a callback passed along with options when there is a dragEnd
event. I want to modify the options
object's dataset when there is a event triggered. How do I get the event outside its scope so that I can do manupulations.
@Component({
selector: 'app-line-chart',
templateUrl: './line-chart.component.html',
styleUrls: ['./line-chart.component.css']
})
export class LineChartComponent implements OnInit {
@ViewChild('myChart') myChart: BaseChartDirective;
public chartInstance: Chart;
public context: CanvasRenderingContext2D;
public options: any = {
type: 'line',
data: {
labels: [2010, 2011, 2012, 2013, 2014],
datasets: [
{
label: 'Marks',
data: [120, 90, 30, 50, 20, 30],
borderWidth: 3,
borderColor: "#00a2e8",
fill: false
}
]
},
options: {
dragDataRound: 0,
dragData: true,
scales: {
yAxes: [{
ticks: {
reverse: false
}
}]
},
onDragEnd: function (e, datasetIndex, index, value) {
console.log('Event Triggered'); // This works fine.
//Here I want to trigger a function outside its scope.
this.dragEndEvent(e, datasetIndex, index, value);
}
}
};
dragEndEvent(e, datasetIndex, index, value) {
//Do some manipulations on the myChartOptions object.
// When this event is triggered, I cannot acccess options object.
// console.log(this.options);
//Error: Cannot read property 'options' of undefined
}
constructor() { }
ngOnInit() {
}
ngAfterViewInit(): void {
this.chartInstance = new Chart(this.myChart.ctx, this.options);
}
}
Upvotes: 2
Views: 829
Reputation: 27293
You have to use arrow functon to refer this context
Try this:
public myChartOptions = {
type: 'line',
data: {...},
options: {
dragData: true,
dragX: false,
dragDataRound: 0,
dragOptions: {
magnet: {
to: Math.round
}
},
onDragEnd: (e, datasetIndex, index, value) => {
console.log('Event Triggered'); // This works fine.
//Here I want to trigger a function outside its scope.
this.dragEndEvent(e, datasetIndex, index, value);
}
}
}
dragEndEvent(e, datasetIndex, index, value) {
//Do some manipulations on the myChartOptions object.
// This is not getting triggered.
}
Upvotes: 4