我将按照此示例以Angular 显示sigmajs图形:https://github.com/sim51/ng-sigma-example.
- 应用程序组件. ts**
import { Component } from "@angular/core";
import Graph from "graphology";
import erdosRenyi from "graphology-generators/random/erdos-renyi";
import circularLayout from "graphology-layout/circular";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"]
})
export class AppComponent {
title = "ng-sigma-example";
graph: Graph;
constructor() {
this.graph = erdosRenyi(Graph, { order: 100, probability: 0.1 });
circularLayout.assign(this.graph);
}
}
- σ分量ts**
import {
Component,
OnDestroy,
AfterViewInit,
ElementRef,
ViewChild,
Input
} from "@angular/core";
import Graph from "graphology";
import { Sigma } from "sigma";
@Component({
selector: "sigma",
template: "<div #container></div>",
styleUrls: ["./sigma.component.scss"]
})
export class SigmaComponent implements AfterViewInit, OnDestroy {
@ViewChild("container") container: ElementRef | null = null;
@Input("graph") graph: Graph = new Graph();
sigma?: Sigma;
ngAfterViewInit(): void {
if (this.container)
this.sigma = new Sigma(this.graph, this.container.nativeElement);
}
ngOnDestroy(): void {
if (this.sigma) {
this.sigma.kill();
}
}
}
- 应用程序.组件. html**
<sigma [graph]="graph"> </sigma>
- 搜索.组件. ts**
import {
Component,
OnInit,
ElementRef,
ViewChild,
Input} from '@angular/core';
import { Sigma } from "sigma";
import Graph from "graphology";
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {
@ViewChild("container") container: ElementRef | null = null; // could be null -> hence needs if statement
@Input("graph") graph: Graph = new Graph();
@Input() // should give me the sigma instance from sigma.component.ts
constructor() {
}
ngOnInit(): void {
// should give me access to sigma instance graph
console.log(this.renderer?.getGraph())
}
}
在sigma. component. ts中创建了一个sigma示例,我的问题是,如何与兄弟组件search. component. ts共享sigma示例?
通常,我会使用@input和@output装饰器以及事件发射器来共享图形,将父组件用作桥梁。但是我在sigma.component.ts模板中只有div标记,并且我无法通过这种方式获得解决方案。我需要在sigma.component.ts中创建/更改新sigma示例时共享sigma示例
1条答案
按热度按时间sy5wg1nm1#
另一种在组件间共享数据的方法是使用Observables的服务。你可以创建一个服务,它的值可以从任何地方更新,并从任何地方监听这些更改。你可以在https://angular.io/guide/observables上阅读更多信息。
sigma服务.ts
sigma.component.ts(不要忘记导入服务并将其添加到构造函数中)
search.component.ts(创建一个订阅变量和sigma变量来填充。当通过订阅接收到新值时,在ngOnInit上填充,不要忘记取消订阅onDestroy)