简体   繁体   中英

Cytoscape Fit function is not working if we have dynamic height calculated using number of nodes

I am using Cytoscape Dagre extension to show hierarchical graph from left to right. It has 14 children and one parent 1 and main parent. I am calculating the height of the container using the number of nodes. Then I am calling fit function after the layout is created but it is not working.

I have added a fit button and if I click on it after the graph is loaded, it works then. What am I doing wrong? I would like fit function to be called after the graph is initialzed.

Here is the stackblitz link: https://stackblitz.com/edit/dagre-childrenconnected-fit?file=src%2Fapp%2Fapp.component.ts

You can try clicking on Fit and see the graph is fitted properly if you click on fit button but it does not work if you refresh the page.

Your code is not working correctly, there are some errors.

(1) Firstly, your "dynamic height" [ngStyle]="{'height': heightTest + 'px'}" is undefined at graph init and runs into a weird error after that. Just use something like [ngStyle]="{'height': '100vh'}" and go from there.

(2) As the docs say:

If your code resizes the graph's dimensions or position (ie by changing the style of the HTML DOM element that holds the graph, or by changing the DOM element's position in the DOM tree), you will want to call cy.resize() to have the graph resize and redraw itself.

Your approach is not really ideal, I'd suggest just changing the height of your container and then resizing/fitting your graph:

let container = document.getElementById("cy");
// just some random height depending on the number of nodes
container.style.height = `${this.cy.nodes().length * 40}px`;

this.cy.resize();
this.cy.fit();

Here is the edited StackBlitz: link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM