角度2和图表.js交互



我目前正在处理图表中的一些图表.js,我正在添加一些与它们的简单交互,当用户单击条形图中的条形时,变量会保存单击的条形。

此变量更新折线图,

此图表使用以前保存在数组中的数据进行更新,因此每次用户单击与条形图不同的条形时,折线图都应更改。

我的问题是变量没有改变,我得到了两个不同的值。默认情况下,变量初始化为 0。

控制台日志输出:

from barchart click:3   
from change function:0 
from barchart click:2  
from change function:0

我从同时发生的 2 个不同功能打印这些行。

这是在条形图上单击条形图时应更改变量值的函数。

  graphClickEvent(event:any, array:any){
    if(array[0]){
       this.offsetGraficas = array[0]._index;
     console.log("from barchart click:"+this.offsetGraficas);
    }
}

以及同时发生的其他功能:

changeHistorico(n:number) {
   console.log("from change function:"+this.offsetGraficas);
    this.show_historico = true;
    //some unrelated code goes here
}

从我所看到的,graphClickEvent 首先执行,但我没有看到变量的任何变化。为什么它不能按预期工作?

看起来 graphClickEvent 中的 "this" 和 changeHistorico 中的 "this" 是不同的。

是的,点击事件中的this与父组件的this不同。
全局变量是一种方式。

但更好的解决方案是传递组件实例是图表.js图形的配置。

this.dsChart2 = new Chart(myCtx2,{
  type: 'pie',
  parentInstance: this,
  data: { ... }
  options:{
    onClick: this.graphClickEvent
  }
}

现在,当调用graphClickEvent时,您将获得两个值,事件和图表实例,您已经从中获取索引值。

所以现在从点击事件函数中,你可以引用parentInstance,如下所示:

graphClickEvent(evt,item) {
  console.dir(item);
  let parentThis = item[0]['_chart']['config']['parentInstance'];
  // here parentThis is the component this or $scope
  parentThis.variable = value;
}

最新更新