Is it possible to invoke a component's function within the click function of a Chartjs chart?

How do I trigger a function in my Component from an onclick event in my chart.js?

export class ReportesComponent implements OnInit {

  constructor(public _router: Router, private data: ReporteService) {}
  
  this.chart = new Chart('myChart', {
    type: 'bar',
    data: {
      labels: this.barCharLabels,
      datasets: [
        { 
          data: this.dataCharCartera,
          label: 'Cartera',
          backgroundColor: 'rgb(232,95,95)'
        },
        { 
          data: this.dataChar,
          label: 'Penetracion',
          backgroundColor: 'rgb(95,145,232)'
        }
      ]
    },
    options: {
      legend : {
        display: true
      },
      responsive: true,
      scales: {
        xAxes: [{
          ticks: {
            beginAtZero: true
          }
        }]
      },
      onClick: (e) => {
        var element = this.getElementAtEvent(e);
        if (element.length) {
           console.log(element[0]._view.label)
        }
        console.log(element);
        this.Showtest(e);
      }
    }
  });

  Showtest(e): void {
    console.log(e)
    this._router.navigate(['/Menu/Informacion']);//
  }

}

I am looking to call the Showtest function and retrieve the element value within the onClick function of my chart.js. Thank you.

Answer №1

Sure, binding is possible with chartjs plugin. However, since the plugin is element based, you will need to create a directive in order to apply any jQuery or element based approach.

Here is a solution for your query. The key is to assign the component to another variable and access it within the chartjs click function. This way, you can pass any desired data.

    ngAfterViewInit() {
    this.canvas = this.mychart.nativeElement; 
    this.ctx = this.canvas.getContext('2d');
    let $this = this;
    let myChart = new Chart(this.ctx, {
      type: 'bar',

      data: ...,
      options: {
          legend : {
            display: true
          },
          responsive : true,
          scales : {
            xAxes :[{
              ticks:{
                beginAtZero: true
              }
            }]
          },
          onClick: function (e) {
            debugger;
            var element = this.getElementAtEvent(e);
            if (element.length) {
               console.log(element[0]._view.label)
            }
            $this.Showtest(e, this, element);
          },
          //onClick: this.Showtest.bind(this),
        }
    });
  }

  Showtest(event, chart, element) : void {
    debugger;
  }

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 in Angular 7.2.0: Attempting to assign a value of type 'string' to a variable of type 'RunGuardsAndResolvers' is not allowed

Encountering an issue with Angular compiler-cli v.7.2.0: Error message: Types of property 'runGuardsAndResolvers' are incompatible. Type 'string' is not assignable to type 'RunGuardsAndResolvers' This error occurs when try ...

Can you identify the TypeScript type for an array containing various Angular components?

In my application, I have a diverse range of components that I would like to organize into an array. There are no restrictions on what types of components can be included in this array, as long as they are Angular components. What is the correct way to de ...

Breaking down arrays in Typescript

Let's say I have an array like this: public taskListCustom: any=[ {title: 'Task 1', status: 'done'}, {title: 'Task 2', status: 'done'}, {title: 'Task 3', status: 'done'}, {title: 'Task ...

Exploring Next.js 13: Enhancing Security with HTTP Cookie Authentication

I'm currently working on a web app using Next.js version 13.4.7. I am setting up authentication with JWT tokens from the backend (Laravel) and attempting to store them in http-only cookies. Within a file named cookie.ts, which contains helper functio ...

utilize the useRef hook to display the total number of characters within a text area

Introducing the following component: import React from 'react'; export interface TexareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> { maxLength?: number; id: string; } export const Textarea = React.forwardRef( ( ...

Tips on ensuring that only one Angular Material expansion panel expands at a time

I have designed a mat expansion panel and I would like to ensure that only one panel can be expanded at a time. In other words, I want it so that when one record is expanded and I click on another record of the mat expansion, the previously expanded reco ...

Utilizing TypeScript: Importing a typed module within a d.ts file (from an npm package)

I am currently working on integrating a definition file into an npm package that has dependencies on React. The specific library in question can be found at https://github.com/eiriklv/react-masonry-component. In my TypeScript project, I have successfully ...

Switch on ngbAccordion via TypeScript File

I need to implement a function in my component.ts file that will toggle the accordion using a button. Can you help me with the script for this? This is my HTML code: <button (click)="toggleAcc()" type="button" class="btn btn-pr ...

Using an additional router-outlet in an Angular 2 application: a step-by-step guide

I have been facing an issue with my angular2 app where I am attempting to use 2 router-outlets. Despite reading numerous blogs and conducting multiple Google searches, I have not been able to make it work. I would greatly appreciate any suggestions on why ...

Modify capital letters to dashed format in the ToJSON method in Nest JS

I am working with a method that looks like this: @Entity() export class Picklist extends BaseD2CEntity { @ApiHideProperty() @PrimaryGeneratedColumn() id: number; @Column({ name: 'picklist_name' }) @IsString() @ApiProperty({ type: Str ...

What is the best way to emphasize specific months and years in an Angular Material datepicker?

I have an array of days, which can be from any year. I am attempting to customize the Angular Material datepicker to highlight specific months and years in the selection views based on the array of days. .html <input [matDatepicker]="picker" ...

Retrieving header information in Angular 6

I am currently working on an example that I found on this website, but I seem to be facing an error that I can't figure out. Even after carefully reviewing my code, I'm still unable to pinpoint the mistake. Specifically, when I use "response =&g ...

Implementing computed properties: A guide to incorporating type setting

I currently have two separate interfaces defined for Person and Dog. interface Person { name: string; weight: number; } interface Dog { name: string; mass: number } const specificAttribute = isDog ? 'mass' : 'weight'; ...

Can we streamline a generic overloaded function's signature to make it more concise?

I have developed a streamlined Axios wrapper function that integrates zod-parsing and presents a discriminated union for improved error handling. While the implementation successfully maintains the default behavior of Axios to throw errors in certain cas ...

Executing a function within another function using Vue.js (axios)

When I make a call to this.func1() within func2, func1 returns undefined. Can anyone offer some assistance? It seems like the function is returning nothing because axios is not finished yet. How can I resolve this issue? func1:function(val){ if(val.x == ...

The form is not valid because the CustomValidator was triggered on a field that was not required

Here is the form setup: this.form = new FormGroup({ someField: new FormControl(''), someOtherField: new FormControl(''), cpf: new FormControl('', [ CustomFormValidators.isValidCPF ]), }); And t ...

What are the steps to effectively troubleshoot TypeScript code in Visual Studio 2017?

Currently working on an ASP.NET Core project that heavily utilizes TypeScript. Does Visual Studio support debugging TypeScript code? ...

Is there a method to categorize an array of objects by a specific key and generate a new array of objects based on the grouping in JavaScript?

Suppose I have an array structured like this. It contains objects with different values but the same date. [ { "date": "2020-12-31T18:30:00.000Z", "value": 450 }, { "date": "20 ...

Troubleshooting connectivity problems: SocketIO integration with microservices on a Kubernetes platform

I have organized my system using microservices architecture, with separate services for client interactions, orders, payments, and more. Each of these services runs on its own express server. Now, I am looking to integrate real-time feedback functionality ...

Exploring techniques to compare two objects in JavaScript and then dynamically generate a new object with distinct values

var person1={ name:"Sarah", age:"35", jobTitle:"Manager" } var person2={ name:"Sarah Sanders", age:"35", jobTitle:"Manager" } //the name value has been updated in the above object, s ...