Using TypeScript to pass a callback function to labelFormatter in the legend of a Highcharts chart

I am currently experimenting with integrating HighCharts into an Angular2 project using TypeScript.

My goal is to customize the appearance of the legend text, adding an image next to it. I've found that HighCharts provides a labelFormatter property within the legend section for this purpose.

http://api.highcharts.com/highcharts#legend.labelFormatter

The labelFormatter function allows you to modify the format of each series' labels. When used, 'this' refers to either the series object or, in the case of pie charts, the point object. By default, the series or point name is displayed.

However, I'm struggling to figure out how to pass a callback function from TypeScript to the labelFormatter property.

updateChart(): void {
    let newOptions = {
        legend: {
            useHTML: true,
            itemMarginBottom: 10,
            enabled: true,
            floating: true,
            align: 'center',
            verticalAlign: 'top',
            labelFormatter: (s) => this.getLegendLabel(s),
            y: 35
       }
    }
}

getLegendLabel(seriesDetails) {
    console.log(seriesDetails);
}

When executing this code, I am encountering an issue where the seriesDetails object is returning as undefined.

Additionally, whenever I use the this keyword, it references the component itself rather than the series information.

Answer №1

As stated in the details provided by the official documentation:

The callback function is used to format each label of the series. The keyword "this" refers to either the series object or the point object in the case of pie charts. By default, the name of the series or point is displayed.

It appears that there might be an issue with how you are using "this" in the fat arrow function. In my opinion, the easiest solution would be to simply adhere to the syntax outlined in the documentation (jsfiddle):

labelFormatter: function () {
    return this.name + ' (click to hide)';
}

Answer №2

When writing your code, make sure to follow this structure:

updateChart(): void {
    let newOptions = {
        legend: {
            useHTML: true,
            itemMarginBottom: 10,
            enabled: true,
            floating: true,
            align: 'center',
            verticalAlign: 'top',
            labelFormatter: this.getLegendLabel,
            y: 35
       }
    }
}

getLegendLabel() {
    console.log(this);
}

By implementing the above code, you will generate the following JavaScript code that functions correctly within the specified class name ('Test'):

Test.prototype.updateChart = function () {
    var newOptions = {
        legend: {
            useHTML: true,
            itemMarginBottom: 10,
            enabled: true,
            floating: true,
            align: 'center',
            verticalAlign: 'top',
            labelFormatter: this.getLegendLabel,
            y: 35
        }
    };
};
Test.prototype.getLegendLabel = function () {
    console.log(this);
};

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

Error encountered: Uncaught SyntaxError - An unexpected token '<' was found while matching all routes within the Next.js middleware

I am implementing a code in the middleware.ts file to redirect users to specific pages based on their role. Here is the code snippet: import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' import { get ...

Set the component variable to hold the output of an asynchronous method within a service

As I work on developing an application, I aim to keep my component code concise and devoid of unnecessary clutter. To achieve this, I plan to offload complex logic into a service which will then be injected into the component. Suppose my component includes ...

Exploring Angular Material's Autocomplete feature and staying updated with incoming data changes

https://material.angular.io/components/autocomplete/examples export class AutocompleteAutoActiveFirstOptionExample implements OnInit { myControl = new FormControl(); options: string[] = ['One', 'Two', 'Three']; filtered ...

Issue with res.redirect not properly redirecting to https site

After reading numerous posts with the same title, I have tried several suggestions but none of them have worked. In my Angular2 app with a server API, I am looking to automatically redirect in production if it's not secure. The code below is the fir ...

determine the appropriate month for the calendar month component based on the route selected

I have developed a calendar component where I want to preselect the default month based on the route parameters received for the component. Here is the calendar: <p-calendar [maxDate]="dateTime" [(ngModel)]="selectedMonth" name=&quo ...

Ways to verify if a function has completed execution and proceed to invoke another function

I am seeking to verify if a user has chosen an item from the ngFor form and then redirect them to another page upon submitting the form with the updated value. HTML: <mat-select placeholder="Treatment" [(ngModel)]="model.TreatmentA" name="TreatmentA" ...

Replacing the previous observation

My events app features an all-events component that showcases all the events created. Upon loading the all-events component, the events are fetched from the database. Below is a snippet of the relevant code from the Typescript file of the all-events compo ...

Guide on how to use window.resize subscription in an Angular service?

I have been experimenting with the WindowService in my Angular project. Here is the code I have written: import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; interface WindowSize { width?: number; height? ...

Tips for targeting a specific element with providers in Ionic

By using the specified pattern, I am aiming to achieve a unique toolbar or header for only certain pages. Is there a way to accomplish this without injecting the provider and keeping the page as a standalone? My understanding of Ionic is still developing, ...

Testing event handling in CdkDragDrop functionality

I've been experimenting with unit testing for my Angular application. Utilizing Angular Material, I have a component that incorporates the drag-drop CDK cdk drag-drop API. Here's what the HTML code looks like: <mat-card class="interventionCa ...

What is the proper way to conduct unit testing on a function that is invoked in a service's constructor

Is there a way to verify, within the service's spec file, that a function is invoked in the constructor? Consider the following example: @Injectable({ providedIn: 'root' }) export class myService { constructor() { this.myF ...

Choosing an SVG Circle Using TypeScript

I am facing an issue with selecting a simple SVG <circle> element in my DOM using TypeScript: <svg viewBox="0 0 200 200"> <circle cx="50" cy="50" r="45" id="myCircle"/> </svg> In ...

CSS styling is not being applied to buttons within Ionic 2

I'm completely new to Ionic and hybrid apps as a whole. I've been experimenting with a test app, but for some reason, none of the CSS seems to be working. Could someone please help me figure out what mistake I might have made? Here are my files: ...

Angular has a built-in function to determine the next ID after deletion of some items

I am currently facing a situation where I have a list of contacts in a detailed view and navigating through them using the following code: <nav> <a [routerLink]="['/details', friend.id - 1 ]" *ngIf="!(friend.id == 1)"> P ...

Encountering issues while trying to update npm in a Angular 6 project

Attempting to upgrade npm from version 6.1.0 to 6.4.0 using the command line interface: npm install -g npm Unfortunately, encountered an error during the update process. npm ERR! path /usr/local/lib/node_modules/npm/node_modules/ansi-regex npm ERR! co ...

Adjust the setting for the useHash parameter within the RouterModule during execution

I am faced with a situation where I need to dynamically load my router module option useHash in my Angular application, sometimes with true and other times with false. This decision depends on the server state data that is available in the global window ob ...

Angular 7 - Personalized Name for Formbuilder's Dynamic Form

Currently, I am developing a form builder with Angular: return this.fb.group( { myaccount: [ '', [Validators.required]] } ); When an error message is thrown for an element, I iterate through the form controls and disp ...

What is the method for showcasing a single Observable from an Array of Observables in Angular?

I am facing a challenge with displaying questions from an Observable-Array one by one. Currently, I can only display all the questions at once using *ngFor in my HTML. Here is my component code snippet: import { Component, OnInit } from '@angula ...

The parameter type 'IScriptEditorProps' does not accept arguments of type 'string'

After trying numerous solutions, I decided to integrate this script editor into a SharePoint site. However, when attempting to implement it, I encountered an issue with the constructor lacking arguments. Despite my efforts to troubleshoot, I have been unab ...

Using TypeScript: Functions incorporating properties

Recently, I made an interesting discovery in JavaScript: function foo() { console.log("FOO"); } foo.bar = "FOOBAR"; foo(); // logs "FOO" console.log(foo.bar); // "FOOBAR" This got me thinking: How would I repres ...