Home > other >  'this' in chartJS in Angular
'this' in chartJS in Angular

Time:09-12

This is my chartJS onclick event handler in angular:

legend: {
          onClick: this.toggleLegendClickHandler

From that method I need to update a chart after y scale title text is changed. I would like to do this like this._chart.chart.update() where _chart is childview angular directive.

However, this is not a component object but Legend object which received an event. Can I have this in that handler as angular component object?

CodePudding user response:

Use arrow function to define toggleLegendClickHandler function It will point to component object

export class ChartComponent{
    
    legend: {onClick: this.toggleLegendClickHandler}
    
    toggleLegendClickHandler = ()=>{
    ...
    }
}

CodePudding user response:

You can use this shadow, suppose this is your code,

chartFunction() {
     const _that = this;  // creating shadow of this

    createChart({
    data: {
            legend: {
              onClick: _that.toggleLegendClickHandler
            }
    }
    });

}

now it will refer the component class reference.

  • Related