Trouble with triggering Amcharts click event in Angular 2

Below is the codebase that I am working with:

        export class myComponent implements OnInit {
          minHist;
          maxHist;
        }

        public callAmcharts(whichFilterType:String){

                    this.amchart = AmCharts.makeChart( "chart", {
                      "type": "serial",
                      "theme": "light",
                      "dataProvider": this.TrendData,
                      "valueAxes": [ {
                        "gridColor": "#FFFFFF",
                        "gridAlpha": 0.2,
                        "dashLength": 0
                      }],
                      "gridAboveGraphs": true,
                      "startDuration": 1,
                      "graphs": [ {
                        "balloonText": "[[category]]: <b>[[value]]</b>",
                        "fillAlphas": 0.8,
                        "lineAlpha": 0.2,
                        "type": "column",
                        "valueField": "dCount",
                        "showHandOnHover":true
                      } ],

                      "chartCursor": {
                        "categoryBalloonEnabled": false,
                        "cursorAlpha": 0,
                        "zoomable": false
                      },
                      "categoryField": "dRange",
                      "categoryAxis": {
                        "gridPosition": "start",
                        "gridAlpha": 0,
                        "tickPosition": "start",
                        "tickLength": 20,
                        "labelRotation": 45
                      },
                      "export": {
                        "enabled": true
                      }

                    });

   this.amchart.addListener("clickGraphItem",this.myfunc);

}

After implementing onclick event myfunc, I am facing an issue where I cannot access any global variables using this. This seems to be causing the error message

Uncaught TypeError: Cannot set property 'minHist' of undefined
.

public myfunc(e:any){
        var range= e.item.category;
        let range_arr = range.split("-");
        this.minHist=range_arr[0];
        this.maxHist=range_arr[1];

    } 

Answer №1

Modify

this.amchart.addListener("clickGraphItem",this.myfunc);

to

this.amchart.addListener("clickGraphItem",this.myfunc.bind(this));

You can also use the following based on your inputs:

this.amchart.addListener("clickGraphItem",(e)=> this.myfunc(e));

which is a shorter version of:

this.amchart.addListener("clickGraphItem",(e)=> { return this.myfunc(e); });

For further information, check out: How to access the correct `this` context inside a callback?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I rely on JqTouch for my mobile web development, but I've noticed a strange behavior: whenever I refresh a page that isn't the homepage and then navigate back,

One scenario to consider is as follows: #HOME - #Page1 #Page1 - #Page2 #Page2 - #Page3 Imagine being on #Page3, refreshing the page does not alter the current position. However, if you click the back button, it redirects you to #HOME instead of #Page2. ...

Is there a way to restrict keyboard input on this date picker?

Can you review the following link and let me know which properties or events I should utilize in this scenario? https://codesandbox.io/s/charming-frost-qrvwe?file=/src/App.js ...

Exploring the world of currency trading with Angular2 and live FOREX market charts

Can anyone help me create a candlestick chart in angular2/4 using authentic FOREX market data? I am struggling to find a reliable source for real-time data at the moment. ...

Is it possible to include a variable in the name of my hook state?

My idea is to use the hook in a way that allows for usage like this <Foo id="foo1" /> and <Foo id="foo2" /> export const Foo = () => { const [state + props.id, state + props.id] = useState("foo") return ( ...

What is the Javascript event that fires when a browser loads fresh inline (ajax) content?

I am searching for a JavaScript event that is activated when the browser loads new inline (ajax) content. I want to be able to detect and capture any new content generated within my browser extension. Thank you in advance document.addEventListener('DO ...

What is the process for setting up a Quill Editor within an Angular 2 Component?

I am currently working on creating my own Quill editor component for my Angular 2 project. To integrate Quill into my project, I utilized npm for installation. My goal is to develop a word counter application using this component and I am referring to the ...

What is the process for subscribing when setting up an observable?

There's this situation where I have an observable that emits an ID. My goal is to fetch an element associated with that ID and save it into a new observable. The catch is, the new observable must be subscribed to in order to emit its value. Here' ...

Are there any means to automatically generate placeholder methods and properties for constructor dependencies in Angular?

constructor(private a:dependencyA,private b:dependencyB,private c:dependencyC){ } Here is an example of how dependencyA is structured: export class dependencyA { showPopup: boolean; defaultProperties = { showPopup: this.showPopup, }; priva ...

Can I use jqPlot to create a separate division for the legend?

Is it feasible to move the legend to a distinct div using jqPlot? legend: { show: true, placement: 'outside', fontSize: '11px', location: 'n' } ...

Tips for implementing events with AngularJS Bootstrap Colorpicker

I am having trouble understanding how events function with Angular Bootstrap Colorpicker. I have forked a Plunker from the developer's example. Unfortunately, there are no examples provided for using events. It would be great if events like colorpick ...

Refresh a doughnut chart in real-time using NG2Charts

Currently, I am in the process of developing a macronutrient calculator as part of a project. The idea is to have a form where users can input values, and a corresponding doughnut chart will display with initial values set at 0. However, upon clicking the ...

Box creation in ie7 is malfunctioning

$("div").append($(document.createElement("input")).attr({ 'id': 'post_category', 'value': 'item', 'type': 'checkbox',& ...

Exploring the Logic Behind My State Store Layout - Comparing User Interface to Application State

I'm starting to get a bit confused about the difference between application state and UI state. Whenever a user picks an activity from a list on the page, an API call is triggered to retrieve the announcements for that specific activity. Is the id of ...

Updating "affectedRows: 0" in React Native results in an undefined delete operation

Hello, I am facing some challenges with implementing the Update and Delete functions in my app. When I try to update an item by its id, the output in my app shows nothing and the console.log for the Update function displays "affectedRows:0" without updatin ...

How can I convert Double Quotes from (") to (&quot;) in TinyMce Editor?

While using TinyMce Editor, I have encountered a problem with double quotes breaking my code. In the HTML source of TinyMce, it displays " instead of &quot, causing issues in conversion. It seems that it is not converting " to " as it should, simi ...

Click on a kendo-chip in Angular to copy its content

Can someone assist me in copying the content within a Kendo Chip when clicked in an Angular application? Your help is greatly appreciated. View image here ...

break LineSegment at specified location

Using the vertex positions provided below, I am creating a square using THREE.LineSegments (or even by a simple THREE.Line.) vertices: path.vertices = [ new THREE.Vector3( 3.4000015258789062, 0, 3.4000015258789062 ), new THREE.Vector3( 10.6000061 ...

Activate the Toggle event in Jquery UI Sortable

I have created a basic list that can be sorted using Jquery UI. Within the list, some of the items contain two separate divs - one for the title and another for the content. The title is linked to a toggle event which toggles the visibility of the content ...

AngularJS display function is not functional

I am dealing with an HTML button <button id="postChanges" ng-show="changes.available" data-ng-click="postChanges()">Save</button> and a controller specifically for this view myApp.controller('myController', ['$scope', fu ...

While developing my Typescript project, I encountered the TS2554 error during the build phase but did not face it during the development process

Everything seems to be working fine during development with no warnings or compile errors. However, when running npm build, I encounter the TS2554 error on a constructor stating that it expects 0-1 arguments but is receiving 2. The constructor is defined ...