使用角度指令将是解决此问题的一种干净方法。让我们从安装 vis.js 开始
npm install vis
显示 vis 图表的组件应该有一个图表的容器元素。比方说
图-visualization.component.html
<div [appGraphVis]="graphData" class="graph-container"></div>
图形可视化.component.css
.graph-container {
height: 25em;
widows: 100%;
}
图形可视化.component.ts
import { Component, OnInit } from '@angular/core';
import { DataSet } from 'vis';
@Component({
selector: 'app-graph-visualization',
templateUrl: './graph-visualization.component.html',
styleUrls: ['./graph-visualization.component.css']
})
export class GraphVisualizationComponent {
graphData = {};
constructor() { }
ngAfterContentInit(){
// create an array with nodes
var nodes = new DataSet([
{id: 1, label: 'Node 1'},
{id: 2, label: 'Node 2'},
{id: 3, label: 'Node 3'},
{id: 4, label: 'Node 4'},
{id: 5, label: 'Node 5'}
]);
// create an array with edges
var edges = new DataSet([
{from: 1, to: 3},
{from: 1, to: 2},
{from: 2, to: 4},
{from: 2, to: 5}
]);
// provide the data in the vis format
this.graphData["nodes"] = nodes;
this.graphData["edges"] = edges;
}
}
注意几点:
- 这个组件只计算需要可视化的数据,它不做任何事情,比如操作 DOM 或直接使用 vis.js。由于 vis.js 是一个 DOM 操作,我们可以有一个指令来处理它
- 使用 ngAfterContentInit 而不是 ngOnInit。这将延迟图形生成部分并允许其他 DOM 相关任务完成
graphvis.directive.ts
import { Directive, TemplateRef, ViewContainerRef, Input, Renderer2, ElementRef } from '@angular/core';
import { Network } from 'vis';
@Directive({
selector: '[appGraphVis]'
})
export class GraphVisDirective {
network;
constructor(private el: ElementRef) {}
@Input() set appGraphVis(graphData){
console.log('graph data ', graphData);
var options = {};
if(!this.network){
this.network = new Network(this.el.nativeElement, graphData, options);
}
}
}
为简单起见,我将选项保留在指令中。在现实世界中,选项将作为来自高级组件的另一个输入传递。
附加说明,我们可以为 vis 添加 typescript 的类型以在开发和调试期间提供帮助。它在这里可用:
yarn add @types/vis -D
如果您正在寻找一个现成的解决方案,请查看这个库 - angular-vis。在撰写本文时,它并不支持 vis.js 的所有功能