Tips for invoking both a typescript arrow function and a regular javascript function within one event

Is it possible to call both a JavaScript function and a TypeScript function from the same onClick event in a chart? I am new to TypeScript and Angular, so I'm not sure if this is achievable.

The issue at hand is that I need to invoke a JavaScript function to activate a bar in the chart and a TypeScript function to open a dialog in the Angular component.


    onClick: function(evt){

      console.log(this);//<-- returns chart

      bar: () => {console.log(this)}; //<-- attempting to reference the component here
      bar(); // <-- does not work

      //console.log(document.getElementById('myChart'));
  }

Let's take a look at the complete code snippet:


  public barChartOptions = {
    scaleShowVerticalLines: false,
    responsive: true,
    events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
    onHover: console.log('onHover'),

    onClick: function(evt){
      //console.log(evt); Mouse Event
      console.log(this);
      const getFirst = array => console.log(this);
      console.log(getFirst);
      //bar: () => {console.log(this)};
      //bar();
      //console.log(document.getElementById('myChart'));
  },
    scales: {
      xAxes: [{
        stacked: true
      }],
      yAxes: [{
        stacked: true
      }]
    },
    legend: {
      display: true,
      position: 'right'
    },
    tooltips: {
      enabled: true,
      mode: 'point'
    }
  };

Below is the HTML template:


  my-bar-dialog works!
  <div>
    <div style="display: block">
      <canvas baseChart
              id="myChart"
              [datasets]="barChartData"
              [labels]="barChartLabels"
              [options]="barChartOptions"
              [legend]="barChartLegend"
              [chartType]="barChartType">
      </canvas>
    </div>
  </div>

  <button mat-raised-button (click)="openDialog()">Pick one</button>
  <button (click)="openDialog()">Pick one</button>

In summary, there are two different instances of "this" being returned:


    onClick: function(evt){
      let that = this;
      let bar=()=> {console.log(that.this)};
      bar();

  },

    onClick : (evt, datasets) => {
      if(datasets.length > 0){
        console.log(this);
      }
    },

The first returns a chart, while the second returns the component. However, I require both within the same function to interact with Chart.js API functions as well as component functions.

Shown below is the code for the component:


import { Component, OnInit, Inject } from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';
import { BarChartService } from '../bar-chart.service';
import { barChartClass } from '../barChartClass';

declare var foo: Function;

@Component({
  selector: 'app-my-bar-dialog',
  templateUrl: './my-bar-dialog.component.html',
  styleUrls: ['./my-bar-dialog.component.css'],
})
export class MyBarDialogComponent implements OnInit {

  client: string;
  tenant: string;

  constructor(public dialog: MatDialog, private barChartService: BarChartService) {
    foo();
  }

  barChart: barChartClass;
  public barChartLabels: any;
  public barChartType: any;
  public barChartLegend: any;
  public barChartData: any;

  getBarChart(): void {
    this.barChartService.getMockBarChart().subscribe(
      barChart => this.barChart = barChart
    );
    this.barChartData = this.barChart.barChartData;
    this.barChartLabels = this.barChart.barChartLabels;
    this.barChartType = this.barChart.barChartType;
    this.barChartLegend = this.barChart.barChartLegend;
  }

  public barChartOptions = {
    scaleShowVerticalLines: false,
    responsive: true,
    events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
    onHover: console.log('onHover'),

    onClick: function(evt){
      let that = this;
      let bar=()=> {console.log(that.this)};
      bar();
  },

    scales: {
      xAxes: [{
        stacked: true
      }],
      yAxes: [{
        stacked: true
      }]
    },
    legend: {
      display: true,
      position: 'right'
    },
    tooltips: {
      enabled: true,
      mode: 'point'
    }
  };

  openDialog(): void {
    const dialogRef = this.dialog.open(DialogData, {
      width: '250px',
      data: {client: this.client, tenant: this.tenant}
    });

    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed');
      this.client = result;
    });
  }

  ngOnInit() {
    this.getBarChart();
  }
}

@Component({
  selector: 'dialog-data',
  templateUrl: 'dialog-data.html',
  styleUrls: ['dialog-data.css']
})
export class DialogData {

  constructor(
    public dialogRef: MatDialogRef<DialogData>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData) {}

  onNoClick(): void {
    this.dialogRef.close();
  }

}

Answer №1

In the function, the use of the bar and colon is an attempt to describe its type rather than declare it. To actually declare the function, follow this syntax:

onClick: function(evt) {

    console.log(this);//<-- returns chart

    let bar = () => { console.log(this) };
    bar();

    //console.log(document.getElementById('myChart'));
  }

If you wish to both describe and declare it, use this format instead:

  onClick: function(evt) {

    console.log(this);//<-- returns chart

    let bar: () => void = () => { console.log(this) }; //<-- here I try to get this as component
    bar(); // <--doesnt work

    //console.log(document.getElementById('myChart'));
  }

Answer №2

Prior to using the chart within your component, it is advisable to assign it to another variable like so:

var that=this

Next, in your chart code:

 onClick: function(evt){

      console.log(this);//<-- returns chart

   let   bar= () => {console.log(that)}; //<-- 'that' should reference your component
  
  }

Check out the Stackblitz demo here

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

Angular 7 and Express: No content returned in response body after making a POST request

I am encountering an issue with retrieving the response from a POST request in Angular 7. When I set the API to return "text," everything works as expected. However, when I change the response to JSON, the response body in Angular appears to be null. Test ...

Using JavaScript/jQuery to tally characters

Here is the code snippet that I am currently working with: PHP <input style="color:red;font-size:12pt;font-style:italic;" readonly="" type="text" name="q22length" size="3" maxlength="3" value="50"/> <textarea onkeydown="textCounter(doc ...

Using React-router-dom's Link component can cause styling inconsistencies with material-ui's AppBar Button

Exploring the use of a material-ui Button with react-router-dom's Link is showcased here: import { Link } from 'react-router-dom' import Button from '@material-ui/core/Button'; <Button component={Link} to="/open-collective"> ...

Identifying Changes in Form Values Using jQuery

I am facing a challenge with a dynamic form that needs to detect the field sequence properly. Below is my JavaScript file: var i = 1; $("a.add-line").click(function(){ $("div.items").append( $('<div>').attr('id',&ap ...

The term 'Component' is not a valid JSX component that can be used

'Component' is causing issues as a JSX component The error appears to be within the _app.tsx file of my Next.js project. I've been struggling with this problem since yesterday, encountered it during deployment on Vercel for my Next.js TypeS ...

How to Conceal the <th> Tag with JavaScript

I attempted to conceal certain table elements using JavaScript. For <td> elements, it works fine: function hide(){ var x=document.getElementsByTagName('td'); for(var i in x){ x[i].style.visibility='hidden'; ...

What is the best way to include an external JavaScript file in a Bootstrap project?

I am brand new to front-end development and I'm attempting to create an onClick() function for an element. However, it seems like the js file where the function is located is not being imported properly. I've tried following some instructions to ...

Adding a variable to the .append function in HTML code

I am currently working on a way to include the current date and time when a user comments on a post in my forum. While I have successfully managed to upload the text inputted by the user into the comment section, I am now looking to also dynamically insert ...

Numerous unspecified generic arguments

Imagine a collection of functions, each capable of taking an argument and returning a value (the specifics don't matter): function convertToNumber(input: string): number { return parseInt(input) } function convertToBoolean(input: number): boolean { ...

Angular does not propagate validation to custom form control ng-select

In my Angular 9 application, I am utilizing Reactive Forms with a Custom Form Control. I have enclosed my ng-select control within the Custom Form Control. However, I am facing an issue with validation. Even though I have set the formControl to be requir ...

Update the CSS property according to the selected list item in the slider using Glider JS

Looking to dynamically change the background image in CSS based on the active slide value in Glider.js Here is the CSS: html { background-image: url("https://images.unsplash.com/photo-1496518908709-02b67989c265?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEy ...

React component making an Axios request only receives the initial state as a response

I'm struggling with creating an AJAX call using Axios in React. Despite my efforts, I can't seem to pinpoint where the issue lies. Below is what I currently have within my component: ComponentDidMount() { axios.get('https://jsonplacehol ...

Acquiring JSON-formatted data through the oracledb npm package in conjunction with Node.js

I am currently working with oracledb npm to request data in JSON format and here is the select block example I am using: const block = 'BEGIN ' + ':response := PK.getData(:param);' + 'END;'; The block is ...

Sending an Ajax POST request from a Node.js server

I am running a Node.js server with Socket.IO that communicates with a Python server using Django. I am looking to make a POST request from the Node.js server to the Django server on a specific method without utilizing any jQuery functions due to their depe ...

When attempting to import css-animator in Angular2/Typescript, a 404 error is displayed, indicating that the

Recently, I delved into the world of Angular2 and decided to experiment with some animations using css-animator package.json "dependencies": { "@angular/common": "2.0.0-rc.3", "@angular/compiler": "2.0.0-rc.3", "@angular/core": "2.0.0-rc.3", ...

image source that changes dynamically with a placeholder image

Currently, I am facing a certain issue. Unfortunately, I cannot provide a plunkr example as the image is sourced from a protected site and there are no open URLs available that constantly serve changing images. Additionally, I am unable to use a local anim ...

The error message "TypeError: 'results.length' is not an object" occurred within the Search Component during evaluation

Having trouble with a search feature that is supposed to display results from /api/nextSearch.tsx. However, whenever I input a query into the search box, I keep getting the error message TypeError: undefined is not an object (evaluating 'results.lengt ...

Switch between various height and width options using JavaScript

Is there a way to create a toggle that changes both the height and width of an element when it is clicked? <div class="flexbox-container" id="main" onclick="staybig()">Create Account</div> .flexbox-container { ...

Why is it possible to import the Vue.js source directly, but not the module itself?

The subsequent HTML code <!DOCTYPE html> <html lang="en"> <body> Greeting shown below: <div id="time"> {{greetings}} </div> <script src='bundle.js'></script& ...

What methods can TypeScript employ to comprehend this situation?

There's an interesting scenario when it comes to assigning a variable of type unknown to another variable. TypeScript requires us to perform type checking on the unknown variable, but how does TypeScript handle this specific situation? It appears that ...