Snap nodes to the grid upon loading

I know that grid snapping is related to the draggingTool, but is there a way to snap all nodes to the grid initially? I’m using a tree layout and the issue is when you’re moving a single node it will now be misaligned from the rest.

I have experimented with various grid sizes and node spacing but it’s still finicky


You could try something like:

  myDiagram.moveParts(myDiagram.nodes, new go.Point(0, 0), false);

(However, I’m not sure what you want to do if there are nodes within groups.)

See Diagram | GoJS API

Thanks, that worked!

However, I had to wait for the animations to finish for it to work so I wrapped it in an event listener.

  diagram.addDiagramListener('AnimationFinished', () => {
    // Simulate moving parts to align nodes to the grid
    diagram.moveParts(diagram.nodes, new go.Point(0, 0), false);

FYI, an alternative would be to customize the Layout to do that, which would happen before any animation.

You are right. Running this function after the animation ends up janky as you see the nodes actually move. I changed the event listener to listen to LayoutCompleted. And that fixed it.

Is this what you mean or is there a better/correct way to do this?

Very good. It is also possible to define a subclass of the layout and override commitNodes or commitLayout to call the base method and then snap the nodes.