How can I call an external function in Typescript within an Angular 2 project using C3 js with the c3

I've been struggling with a specific issue for quite some time now, but I can't seem to pinpoint the exact problem. I'm not sure if it's related to Angular or C3.

Oddly enough, I'm unable to execute my method within the c3.generate function from the same component.

The c3 chart is being called from the template and is functioning perfectly fine. I've even tested my somethingMethod() using a button in the template, and it works as expected.

I am trying to invoke the somethingMethod() within the c3 onclick function, but it's not having any effect. Even though an alert message pops up, indicating that I may be out of scope, I'm uncertain about how to resolve this issue.

@Component({
    selector: 'something',
    templateUrl: 'something.component.html',

})
export class SomethingComponent{

    someTypeTitle: string;

    getData(input: string): Array<number>{
        return data;
    }

    somethingMethod(input: string){
        someTypeTitle = input;
    }

    getChart() {
        var chart = c3.generate({
            bindto: '#stackedbar',

            data: {
                x: 'x',
                columns: [
                   this.getData(someString),
                   this.getData(someString) //These work
                ],

                onclick: function (d, e) {
                   alert(this.internal.config.axis_x_categories[d.x]); // This works
                   this.someTypeTitle="asdad"; //This doesn't work.
                   this.someTypeTitle=  this.internal.config.axis_x_categories[d.x]; //This doesn't work.
                   this.somethingMethod(this.internal.config.axis_x_categories[d.x]); //This doesn't work.

                },
}...

Answer №1

Actually, the issue at hand is not related to Angular 2 or C3 specifically; rather, it stems from the intricacies of changing this in ECMAScript.

The crux of the problem lies in this within the onclick function not referencing your class instance. When the function is invoked by C3, C3 executes it within a different context. Consequently, this inside the onclick function points to the element instead of your class instance, which is a common occurrence with event callbacks.

To circumvent this issue, employing an arrow function with lexical this is recommended. With lexical scoping, this within the arrow function retains its original value regardless of the calling context.

Here's how you can use an arrow function:

onclick: (d, e) => {
    this.someTypeTitle = "asdad";
    this.someTypeTitle = this.internal.config.axis_x_categories[d.x];
    this.somethingMethod(this.internal.config.axis_x_categories[d.x]);
}

For further information on arrow functions, visit MDN's guide on arrow functions.

Answer №2

I managed to solve my question by myself since no one responded. I ended up declaring a variable earlier on, assigning it as 'that=this;', and then referencing the functions I needed with 'that.somethingMethod();'

It turns out that 'this' within an onclick function refers to the c3/d3 elements.

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

Managing startup errors in Angular 2

Is there a way to capture startup errors such as compilation or dependency injection errors and display a meaningful message instead of just showing 'loading' on a blank page? Using try/catch with bootstrapModule may work in some scenarios: try ...

Guide to highlighting manually selected months in the monthpicker by utilizing the DoCheck function in Angular

I'm facing an issue and I could really use some assistance. The problem seems quite straightforward, but I've hit a roadblock. I have even created a stackblitz to showcase the problem, but let me explain it first. So, I've developed my own t ...

Comparing performance: Execution time of Core JavaScript versus jQuery

Is it necessary to use jQuery if my purpose can be fulfilled by core JavaScript alone? I am concerned whether using additional libraries like jQuery will slow down the application or not. If anyone has any resources or references on this topic, I would a ...

The implementation of conditional parameter types in TypeScript

I am struggling with a function where the type of the first argument is determined by the second argument's value of true or false According to my logic, if userExists is true, data should be a string and if it's false, data should be a number. ...

Any ideas on how to fix the issue of 'type' property being absent in 'AsyncThunkAction' with Redux Toolkit while working with TypeScript?

While working with Redux Toolkit and the thunk/slice below, I decided to handle errors locally instead of setting them in state. To achieve this, I followed the example provided here. Although I could have set an error in the state, I wanted to explore wh ...

What is the Angular lifecycle event that occurs after all child components have been initialized?

Seeking help with implementing a concept for the following scenario: I have a parent search component containing several child components for displaying facets and search results. I want to automatically trigger a search once the application has finished ...

How to showcase ByteArrayContent using Angular

I have a Web API that has been functioning well for two years in existing Knockout and polymer applications, so I don't want to make any changes to it. Now, I am trying to integrate Angular and need to display an image from the API. Below is the code ...

Getting the parent from a child in Typescript: Best Practices

Querying: In TypeScript, is it possible to retrieve a parent instance from a child instance? I am aware that casting a child into its parent is a method, however, the child's additional properties still exist in the parent, albeit concealed. Check o ...

How can I prevent scrolling in Angular's cdk-virtual-scroll feature?

Is there a way to use Angular's cdk-virtual-scroll to prevent the scrollbar from moving by default? I have done extensive research but have not been able to find a solution. ...

Encountered an issue during the migration process from AngularJS to Angular: This particular constructor is not compatible with Angular's Dependency

For days, I've been struggling to figure out why my browser console is showing this error. Here's the full stack trace: Unhandled Promise rejection: NG0202: This constructor is not compatible with Angular Dependency Injection because its dependen ...

The modal remains closed: Error - Attempting to access property 'open' of undefined

I've been attempting to showcase a pop-up that I implemented as a modal, but I keep getting this error: TypeError: Cannot read property 'open' of undefined The pop-up was created as a component: import { Component, OnInit, ViewChild, Ele ...

Having trouble with animation transition in Angular 6?

When it comes to animating the opening and closing of a Sidenav, what are some best practices? animations: [ trigger('slider', [ state('open', style( {} )), state('closed', style( ...

What is the best way to extract the id from a URL in an Angular Resolver component?

I am currently using a resolver component, but I am facing issues with extracting the id from the URL. Check out the Stackblitz example here - https://stackblitz.com/edit/angular-x4djgz When I navigate to supplier/3 in the Stackblitz: I notice that I ge ...

Angular TypeScript state management system

I am facing a challenge in connecting a controller to a state (using angular ui.router) where one way of writing it works, while the other does not. Successful example (with the controller registered under the module): this.$stateProvider .state(' ...

A similar functionality to the async pipe in TypeScript

In my Ionic2 project, I'm utilizing ng-translate from ng2-translate to translate strings in the code. Currently, I am using the service in the following way: translate.get('ERROR').subscribe((res: string) => { //The translated string ...

Using forEach with switch cases in Angular5 (TypeScript)

I am trying to work with a basic array of languages and a switch function, but I am having trouble using the forEach method on the cases. It would be really helpful as there are numerous languages in the world! ;) public languages = ["en", "de"]; public s ...

What is the best way to link the data from the HTML input to the class property in the TypeScript file? (Combining Angular and IntroJs)

I'm working on an onboarding screen with Intro.js and need help with receiving user input. I've been trying different methods like [(ngModel)] = checked, [(checked)] = checked, (checked) = checked, but haven't had any success. Can anyone pro ...

How can I place an Object in front of an Array in JavaScript?

Currently, I am working on an Angular project where I need to modify a JSON array in order to display it as a tree structure. To achieve this, the objects in the array must be nested within another object. Desired format / output: this.nodes = [ { id ...

Creating custom web components with routing in Angular 6

Is it possible to create an Angular WebComponent or Custom Element with routing modules in Angular 6? I have successfully created a web component with atomic components and now I want to expand it to have multiple screens using the routing module. Here ar ...

Creating custom designs for Material UI components

Although not a major issue, there is something that bothers me. I am currently using react, typescript, and css modules along with . The problem arises when styling material ui components as I find myself needing to use !important quite frequently. Is th ...