How to navigate the component from NVD3 Callback in Angular 4?
Asked Answered
S

1

6

I have implemented NVD3 Charts in Angular 4. written an on Click event inside a callback function, on click of the chart I am trying to navigate to another component but I am unable to navigate.

Code :

import { Router} from '@angular/router';
export class MyNewComponentComponent implements OnInit {
constructor(public router: Router)
  {

  }
 this.options = {
    chart: {
      type: 'discreteBarChart',
      height: 450,
      margin : {
        top: 20,
        right: 20,
        bottom: 50,
        left: 55
      },

      x: function(d){return d.label;},
      y: function(d){return d.value;},
      showValues: true,
      valueFormat: function(d){
        return d3.format(',.4f')(d);
      },
      duration: 500,
      xAxis: {
        axisLabel: 'X Axis'
      },
      yAxis: {
        axisLabel: 'Y Axis',
        axisLabelDistance: -10
      },
      callback: function(chart){ 
        chart.discretebar.dispatch.on('elementClick', (angularEvent,e) => {
             console.log("Inside click"); 
                            this.router.navigate(["/app-new-component2"]); 


        });

      }

    }
  }

}

I am getting this error in Console. Could not able find the component reference to redirect. enter image description here

Awaiting Suggestions. Thanks In Advance ..

Sapsucker answered 9/9, 2018 at 15:57 Comment(0)
V
7

So your problem is right here

  callback: function(chart){ // note the callback function
    chart.discretebar.dispatch.on('elementClick', (angularEvent,e) => {
         console.log("Inside click"); 
         this.router.navigate(["/app-new-component2"]); 
    });

  }

So where your callback is, you are using an es5 function() which means anything within that function will not hold the global scope this and instead create a new scope. So in this case when you do this.router.navigate your not referring to the component (global this) your referring to the functions scope this which does not have a router. So what you want to do is this,

  callback: (chart) => { 
    chart.discretebar.dispatch.on('elementClick', (angularEvent,e) => {
         console.log("Inside click"); 
         this.router.navigate(["/app-new-component2"]); 
    });

  }

using an ES6 (fat arrow) function () => {} will keep the global scope this which will let you use your router.

Vibrant answered 12/9, 2018 at 4:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.