TreeLayout default collapse level

I want to configure default collapse level for TreeLayout. Please check below code segments

<gojs-diagram #sngHierarchy [divClassName]='diagramDivClassName' [initDiagram]='initDiagram'
                  [linkDataArray]='state.diagramLinkData' [modelData]='state.diagramModelData'
public initDiagram = (): go.Diagram => {
      this.diagram.addDiagramListener('InitialLayoutCompleted', (e: any) => {
            e.diagram.findTreeRoots().each((r: any) => {
                r.collapseTree(2); // set default collapse level 2

However this is not working as expected. If console out e.diagram.findTreeRoots() it’s values are empty. Maybe I am using incorrect Listener?

Doing the collapse in an “InitialLayoutCompleted” DiagramEvent listener is OK.
An alternative is to default Node.isTreeExpanded to false and then call Node.expandTree instead on each root.

If diagram.findTreeRoots().count === 0, then either you have no Nodes or there is at least one Link coming into each Node. So the graph is not tree-structured.

Actually graph is tree-structured. Here is a screenshot

What I want is below in initial loading

If I change InitialLayoutCompleted to LayoutCompleted intial loading is exactly same as second screenshot (which I want). But then can not expand collpased nodes as nothing happens

So, what was the value of diagram.findTreeRoots().count?

It shows 0

Well, because you definitely have some Nodes, you must have some unexpected Links. Examine the Diagram’s Nodes or the GraphLinksModel carefully.

Looks like nodes and links model is correct. Because If I change InitialLayoutCompleted to LayoutCompleted it works. But then I can not expand collpased nodes as nothing happens

If you do not want to change your graph to be tree-structured, you will need to find the root nodes some other way.

Collapsing or expanding nodes will result in a layout, so such a “LayoutCompleted” listener would keep collapsing trees.