如何将mxgraph与Angular 4集成?求可行方案及示例
我之前也折腾过mxGraph和Angular 4的集成,踩过不少坑,给你梳理个可行的步骤和示例思路,应该能帮到你:
mxGraph与Angular 4集成的完整步骤与示例
一、准备mxGraph资源
- 从mxGraph官网下载压缩包,解压后把
javascript文件夹完整复制到Angular项目的assets/mxgraph目录下,最终路径类似src/assets/mxgraph/javascript/
二、配置Angular CLI脚本
打开项目根目录的angular-cli.json(Angular 4用的是这个配置文件,不是后来的angular.json),找到scripts数组,添加mxGraph的核心脚本:
"scripts": [ // 其他已有的脚本 "./assets/mxgraph/javascript/mxClient.js" ]
三、解决TypeScript类型报错
因为mxGraph没有官方的TypeScript类型定义,我们需要手动声明全局变量:
- 在项目的
src目录下新建typings.d.ts文件(如果已经存在就直接编辑) - 添加以下声明:
declare var mxClient: any; declare var mxGraph: any; declare var mxCell: any; declare var mxGeometry: any; declare var mxEvent: any; // 后续用到其他mxGraph对象时,都可以在这里补充声明
四、组件中实现mxGraph示例
新建一个GraphComponent,按以下步骤编写代码:
1. 模板文件(graph.component.html)
添加一个div作为图形的容器:
<div #graphContainer style="width: 800px; height: 600px; border: 1px solid #e0e0e0;"></div>
2. 组件类(graph.component.ts)
在ngAfterViewInit生命周期钩子中初始化mxGraph(必须等DOM渲染完成后再操作):
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-graph', templateUrl: './graph.component.html', styleUrls: ['./graph.component.css'] }) export class GraphComponent implements AfterViewInit { @ViewChild('graphContainer') graphContainer: ElementRef; ngAfterViewInit(): void { // 先检查浏览器兼容性 if (!mxClient.isBrowserSupported()) { alert('当前浏览器不支持mxGraph,请更换浏览器重试'); return; } // 获取DOM容器 const container = this.graphContainer.nativeElement; // 创建mxGraph实例 const graph = new mxGraph(container); // 开启基础交互:允许节点连接、禁用多图模式 graph.setConnectable(true); graph.setMultigraph(false); // 获取图形的根节点容器 const parent = graph.getDefaultParent(); // 开启编辑事务(批量操作提升性能) graph.getModel().beginUpdate(); try { // 添加两个示例节点 const v1 = graph.insertVertex(parent, null, 'Hello', 20, 20, 80, 30); const v2 = graph.insertVertex(parent, null, 'World', 200, 150, 80, 30); // 添加节点间的连接边 graph.insertEdge(parent, null, '', v1, v2); } finally { // 结束事务,渲染图形 graph.getModel().endUpdate(); } // 可选:添加点击事件监听 graph.addListener(mxEvent.CLICK, (sender, evt) => { const cell = evt.getProperty('cell'); if (cell) { console.log('点击了节点/边:', cell.value); } }); } }
3. 样式调整(graph.component.css)
可以自定义mxGraph的样式,避免和Angular默认样式冲突:
.mxGraph { background-color: #f5f5f5; } .mxVertex { fill: #ffffff; stroke: #2196f3; stroke-width: 2; } .mxEdge { stroke: #757575; stroke-width: 1; }
五、额外注意事项
- 如果需要使用mxGraph的弹窗、工具栏等UI组件,记得把
assets/mxgraph/javascript/css/mxClient.css添加到angular-cli.json的styles数组中,避免样式错乱。 - 不要在
ngOnInit中初始化mxGraph,此时DOM元素还未渲染,会导致容器获取失败。 - 复杂场景下可以封装mxGraph为服务,在多个组件中复用实例和逻辑。
内容的提问来源于stack exchange,提问作者sa_1130
相关产品推荐
相关产品推荐

