Picking up Angular component property values within a callback function from Google Charts

Trying to utilize the angular-google-charts library in Angular 13.2, I am working on creating a TreeMap with a customized tooltip feature. The GoogleChartComponent offers an options property called generateTooltip which requires a callback function. My goal is to access data stored within the Angular component (specifically chart.data) from within this callback function. Unfortunately, I have been struggling to retrieve the component's property while inside the callback function. The examples available on Google's website are primarily focused on standard JavaScript implementations.

<!-- dashboard.component.html -->
<google-chart
  [data]="chart.data"
  [options]="chart.options"
  [title]="chart.title"
  [type]="chart.type"
  [columns]="chart.columns"
  [height]="chart.height"
  style="width: 100%"
></google-chart>
// dashboard.component.ts
import { Component, OnInit } from '@angular/core'
import { ChartType} from 'angular-google-charts'

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
  public chart = {
    title: '',
    type: ChartType.TreeMap,
    data: [
      ['Global', null, 0, 0, 'Global'],
      ['Americas', 'Global', 0, 0, 'Global'],
      ['EMEA', 'Global', 0, 0, 'Global'],
      ['Acme - Lab 1YR (New)', 'Americas', 326000, 100, 'Susan Moore'],
      ['Flexa - DevOps 1YR (New)', 'Americas', 206000, 0, 'Jeremy Young'],
      ['Organo - CI/CD 1YR (New)', 'EMEA', 188000, 0, 'Sif Nilsen'],
      ['Ny Carlsberg Glyptotek - Automated Test Lab 300 devices 1YR (New)', 'EMEA', 212000, 0, 'Nils Peter Bjørnsen'],
      ['Dunder Mifflin - SCM 2YR (New)', 'Americas', 448000, 50, 'Justin Case']
    ],
    columns: [
      {type: 'string', label: 'Opportunity', role: 'domain'},
      {type: 'string', label: 'Parent', role: 'data'},
      {type: 'number', label: 'Amount', role: 'tooltip'},
      {type: 'number', label: 'Score', role: 'data'},
      {type: 'string', label: 'Owner', role: 'tooltip'}
    ],
    options: {
      minColor: '#f00',
      midColor: '#ddd',
      maxColor: '#0d0',
      headerHeight: 0,
      fontFamily: 'Nunito',
      fontSize: 13,
      fontColor: 'black',
      generateTooltip: this._showFullTooltip
    },
    height: 290,
  }

  constructor () {
  }

  _showFullTooltip(row: number, size: number, value: number) {
    // This is where I need to get values out of this.chart.data[row]
    const amount = size.toLocaleString('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 });
    const tooltip = `<div style="color:#fff; background:#313A4B; padding: 10px; border-width:1px; border-style: solid; border-color:#fff;">${amount}</div>`
    return tooltip;
  }

}

The current issue arises when trying to grab pertinent information using the row parameter within the callback that gets passed. Directly accessing this.chart.data[row] has proven to be unsuccessful. It seems like the problem might stem from the interaction between the callback function and Angular itself. Are there any suggestions or best practices for connecting the _showFullTooltip() function with component properties effectively?

Answer №1

The issue at hand is not related to Angular, but rather a JavaScript scoping problem. Instead of simply assigning

generateTooltip: this._showFullTooltip
, make sure to bind the scope to the function like this -
generateTooltip: this._showFullTooltip.bind(this)
.

When you pass a function reference, the context of this will be determined by whoever or whatever is calling that function. By using .bind(this), you can set the context of the function to the current assignee (DashboardComponent). This adjustment should enable you to access this.chart.data[row] within your _showFullTooltip function.

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

Tips for identifying and handling a 400 bad request error in an HTTP response within an Angular 2 application

I attempted to handle the error 400 bad request in this manner: catch((error: any) => { if (error.status === 500) { return Observable.throw(new Error(error.status)); } else if (error.status === 400) { console.log( 'err ...

Utilizing callback functions, promises, and return statements in Node Js

I'm relatively new to using Node.js and despite reading numerous explanations and trying various solutions, I still struggle with understanding function callbacks. //app.js file var dashboardfunc = require('./models/admindashboard'); app ...

How can Angular CLI prevent the submission of an HTML form unless a previous option has been selected

I am currently working on a form that contains select fields with various options pre-populated. <form [formGroup]="selectVehicleForm"> <select formControlName="Manufacturer"> <option *ngFor='let ...

I am experiencing issues with my Angular2 project where not all of my component variables are being passed to the

My problem involves sending three variables to my HTML template, but it only recognizes one of them. The HTML template I am using looks like this: <div class="page-data"> <form method="post" action="api/roles/edit/{{role?.ID}}" name="{{role? ...

There seems to be a malfunction with the routing feature in the src/index.html file

My routing setup is not functioning as expected in src/index.html angular. What I have is a header with some links for navigation: <header> <div class="logo"> <div class="logo-img-div"> <img src="../../ass ...

Learn how to generate a JSON data table for Google Charts with data from MySQL using a custom PHP function. Check out a fully functional example to see how it all works. Is

I recently completed a personal project involving PHP and MySQL, where I fetched data from the database, encoded it to JSON format (including column information), and then visualized it using Google Data Table with Ajax. The project was successful, but I ...

Problem with setting headers in Express Async: Is a double callback causing headers to be sent twice?

I've encountered a frustrating issue with 'Error: Can't set headers after they are sent.' in my Express code. This problem arose after switching from Restify to Express, and despite making necessary adjustments, the error persists. The ...

Troubleshooting problem with toggling Bootstrap accordion

Hello there! I'm currently using a bootstrap accordion within Angular, but I'm experiencing some issues with toggling. I've provided a reference to the stackblitz I created, but I can't seem to identify the cause of the toggling problem ...

Prisma : what is the best way to retrieve all elements that correspond to a list of IDs?

I'm currently implementing Prisma with NextJs. Within my API, I am sending a list of numbers that represent the ID's of objects in the database. For example, if I receive the list [1, 2, 12], I want to retrieve the objects where the ID is eithe ...

Using TypeScript to wrap a class with a Proxy object

I've been working on a function that takes an API interface (I've provided a sample here) and creates a Proxy around it. This allows me to intercept calls to the API's methods, enabling logging, custom error handling, etc. I'm running i ...

Encountering unusual results while utilizing interfaces with overloaded arguments

I came across a situation where TypeScript allows calling a method with the wrong type of argument. Why doesn't the TypeScript compiler flag this as an issue? interface IValue { add(value: IValue): IValue; } class NumberValue implements IValue { ...

Transform ECMAScript Observable / Zen Observable into RXJS Observable

I currently have an ECMAScript Observable that is compliant with specifications, specifically sourced from the wonka library. I am facing challenges in converting this type of observable to an rxjs 6 observable. It appears that this conversion was possibl ...

How can I assign two different colors based on the type in Typescript?

I am configuring a color property based on the nature of the display. colorStyle: { textAlign: "center", backgroundColor: "transparent", color: (theme.colors.BaseColor.Red as any).Red4, } The cu ...

Enhancing CKEditor functionality with Angular 2 for improved textarea usage

Check out this Plunker example: https://plnkr.co/edit/aUBtpe?p=preview When using CKEditor, the value of the content variable does not update when changes are made to the textarea. It remains the same as the original page.content variable that was obtaine ...

Retrieve JSON web token from HTTP header following backend SAML2 authentication

I am facing a challenge in my Angular application where I need to read the JWT from the HTTP header after being redirected from the backend. Here is an overview of my authentication process: Once the user logs in successfully on the web browser, a POST r ...

I am attempting to incorporate an NPM package as a plugin in my Next.js application in order to prevent the occurrence of a "Module not found: Can't resolve 'child_process'" error

While I have developed nuxt apps in the past, I am new to next.js apps. In my current next.js project, I am encountering difficulties with implementing 'google-auth-library' within a component. Below is the code snippet for the troublesome compon ...

Testing a React component that utilizes RouteComponentPropsTesting a React component with RouteComponentProps

One of my components has props that extend RouteComponentProps defined as follows: export interface RouteComponentProps<P> { match: match<P>; location: H.Location; history: H.History; staticContext?: any; } When I use this component i ...

Angular compilation alerted about a missing export: "ɵɵdefineInjectable was not located within '@angular/core'

I'm having an issue while trying to run my Angular application. The error message related to the "ngx-mqtt": "^6.6.0" dependency keeps popping up even though I have tried changing the versions multiple times. I am using CLI 6.2.9 and cannot seem to re ...

Angular 14: A collection and schematic must be provided for execution to proceed with the process

I've recently started learning angular. After installing the latest version, I created an app called "test" using the command ng new test. Next, I opened the app in Visual Studio Code and tried to create a new component by entering the command: ng g ...