Angular中AnyChart甘特图点击行后修改变量文本失败求助
解决Angular中AnyChart甘特图行点击事件无法修改组件变量的问题
我之前在Angular里用AnyChart做甘特图时也踩过这个坑!你猜得没错,核心问题就是事件监听器里的上下文(this)不对——AnyChart的回调函数默认把this指向了图表的行元素,而不是你的Angular组件实例,所以直接给title赋值根本找不到这个变量。
下面给你两种靠谱的解决方法,附完整示例代码:
方法1:使用箭头函数(最推荐)
箭头函数不会创建自己的this,它会继承外层上下文的this(也就是你的组件实例),这样就能直接访问组件里的title变量了。
import { Component, OnInit } from '@angular/core'; import * as anychart from 'anychart'; @Component({ selector: 'app-gantt-chart', template: `<div id="container" style="height: 500px;"></div> <h2>{{ title }}</h2>` }) export class GanttChartComponent implements OnInit { title = '123'; // 默认值 ngOnInit(): void { // 初始化甘特图示例数据 const data = anychart.data.tree([ { id: '1', name: 'Task 1', actualStart: '2024-01-01', actualEnd: '2024-01-05' }, { id: '2', name: 'Task 2', actualStart: '2024-01-06', actualEnd: '2024-01-10' } ], 'as-tree'); // 创建甘特图实例 const chart = anychart.ganttProject(); chart.data(data); // 设置行点击事件——用箭头函数保留组件的this chart.listen('rowClick', (e) => { console.log('点击了行:', e.item.get('name')); this.title = '567567'; // 现在能成功修改组件变量了! }); // 渲染图表到容器 chart.container('container'); chart.draw(); } }
方法2:用bind(this)绑定上下文
如果你习惯用普通函数写法,也可以通过bind(this)把组件的this绑定到监听器函数上:
// 替换上面的监听部分为: chart.listen('rowClick', function(e) { console.log('点击了行:', e.item.get('name')); this.title = '567567'; }.bind(this)); // 绑定组件的this到函数中
关键点说明
- 不管用哪种方法,核心都是让回调函数里的
this指向你的Angular组件实例,而不是AnyChart的DOM元素。 - 测试的时候可以在回调里加
console.log(this),看看输出的是组件还是图表元素,就能快速判断问题所在。
内容的提问来源于stack exchange,提问作者Kroshandowski
相关产品推荐
相关产品推荐

