You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular点击vis-network节点打开NgbModal报undefined错误如何解决

问题原因

报错核心是this指向错误:你给vis-network的click事件绑定的是普通匿名函数,此时函数内部的this指向的是vis-network的实例对象,而非你的VuePrincipaleComponent组件实例,自然找不到组件里注入的modalService,所以抛出Cannot read properties of undefined (reading 'open')错误。


可运行的完整实现代码

import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
import { Network } from "vis-network";
import { DataSet } from "vis-data"
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { InformationsPageComponent } from '../informations-page/informations-page.component';


@Component({
  selector: 'app-vue-principale',
  templateUrl: './vue-principale.component.html',
  styleUrls: ['./vue-principale.component.scss']
})
export class VuePrincipaleComponent implements AfterViewInit {
  public select: string = "30/01/01"

  networkInstance: any;
  @ViewChild('network') elem: ElementRef;
  constructor(public modalService: NgbModal) {}
  
  openView(nodeId?: number) {
    const modalRef = this.modalService.open(InformationsPageComponent);
    // 可选:如果需要把点击的节点ID传给弹窗组件,可以加下面这行
    // modalRef.componentInstance.nodeId = nodeId;
  }
  
  ngAfterViewInit(): void {
    const container = this.elem.nativeElement;
    const nodes = new DataSet([
      { id: 1, label: 'Node 1', color: "blue", shape: 'diamond' },
      { id: 2, label: 'Node 2' },
      { id: 3, label: 'Node 3' },
      { id: 4, label: 'Node 4' },
      { id: 5, label: 'Node 5' }
    ]);

    const edges = new DataSet<any>([
      { from: 1, to: 3 },
      { from: 1, to: 2 },
      { from: 2, to: 4 },
      { from: 2, to: 5 }
    ]);
    const data = { nodes, edges };
    const options = {
      interaction: { hover: true }
    };
    const network = new Network(container, data, options);
    this.networkInstance = network;

    // 核心修改:用箭头函数绑定外层组件的this,同时加判断仅点击节点时触发弹窗
    this.networkInstance.on("click", (params) => {
      // 只有点击到节点的时候才打开弹窗,点击画布空白区域不触发
      if(params.nodes.length > 0) {
        this.openView(params.nodes[0]);
      }
    })
  }
}

其他可选解决方案

也可以通过bind手动绑定this实现相同效果,写法如下:

this.networkInstance.on("click", function(params) {
  if(params.nodes.length > 0) {
    this.openView(params.nodes[0]);
  }
}.bind(this))

内容的提问来源于stack exchange,提问作者Nicolas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 03:06:03