-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,279
  • 5
  • 22
  • 33
starlight
  • 725
  • 3
  • 13
  • 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
  • 190,482
  • 29
  • 403
  • 383
Sajeetharan
  • 203,447
  • 57
  • 330
  • 376
1

Use arrow function to preserve the context

onClickNode: (url, opts) => {
    this.highlightNodes(url, "nodes", true);
}
Suren Srapyan
  • 62,337
  • 13
  • 111
  • 105
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
  • 31,390
  • 9
  • 89
  • 101