-1

I am working with d3.js in an Angular 4 app. I am trying to call a function, but it throws me an error as ERROR TypeError: this.highlightNodes is not a function.

Here's the code, I was working on:

import {Component, OnInit} from '@angular/core';

declare let d3:any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  ngOnInit() {
    this.networkGraph();
  }

  networkGraph() {
    d3.netJsonGraph("../assets/json/network.json",
      {
        el: "#randomDiv",
        onClickNode: function (url, opts) {
          //Here's the error being thrown
          this.highlightNodes(url, "nodes", true);
        }
      }
    );
  }

  highlightNodes(url, type, initial) {
    console.log("Its working");
  }
}

Using bind(this) is not helping because it is binding locally. Please help me resolve this as how to call the function the proper way.

onetwo12
  • 2,359
  • 5
  • 23
  • 34
starlight
  • 765
  • 3
  • 14
  • 30

3 Answers3

2

This refers to the onClickNode in this case, use arrow function:

onClickNode: (url, opts) => {
   //Here's the error being thrown
   this.highlightNodes(url, "nodes", true);
}
yurzui
  • 205,937
  • 32
  • 433
  • 399
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

Use arrow function to preserve the context

onClickNode: (url, opts) => {
    this.highlightNodes(url, "nodes", true);
}
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
1

When you use function keyword, it hides the scope of this. Use arrow function instead.

Replace this line:

onClickNode: function (url, opts) {

... with this:

onClickNode: (url, opts) => {
FAISAL
  • 33,618
  • 10
  • 97
  • 105