Change wrappingColumn for groupTemplateMap after changing diagram orientation

hi,

We have 2 ordination left to right and top to bottom. 

while changing orientation can we change wrappingColumn in GridLayout for groupTemplateMap which are already plotted?

How?

thanks
Amey

Changing any template won’t have any affect on existing Parts. But you could just set the property on each GridLayout. Maybe something like:

myDiagram.commit(function(diag) {
    diag.nodes.each(function(g) {
        if (g instanceof go.Group) g.layout.wrappingColumn = ...;
      });
  });

getting “Uncaught SyntaxError: Invalid or unexpected token” on below line
myDiagram.commitTransaction(function (diag) {
diag.nodes.each(function(g)�{

did I miss to add any ref? the above code snippet looks very simple. then what must have gone wrong.

I don’t see anything wrong with what I wrote above, so you will need to figure out your code.

PFB our code to achieve the change in layout of groups when ever the flip is occurred.
The new groups layout is as expected but already plotted groups layout is not changing.
We have incorporate your suggestion in the following code:

myDiagram.commit(function(diag) {
        diag.nodes.each(function(g) {
            if (g instanceof go.Group) g.layout.wrappingColumn = ...;
          });
      });

Script:

 var myDiagram, $Go;
var angle = 90;

//Data
var nodeLinks = [{ "from": -1, "to": "d_-1" }, { "from": "d_-1", "to": "0" }, { "from": "d_-1", "to": "12" }, { "from": "d_-1", "to": "30" }, { "from": "d_-1", "to": "11" }, { "from": "d_-1", "to": "20" }, { "from": "d_-1", "to": "6" }, { "from": 0, "to": "d_0" }, { "from": "d_0", "to": "-2_7" }, { "from": "d_0", "to": "13" }, { "from": 1, "to": "2" }, { "from": 2, "to": "3" }, { "from": 3, "to": "4" }, { "from": 4, "to": "d_4" }, { "from": "d_4", "to": "5" }, { "from": "d_4", "to": "32" }, { "from": 5, "to": "-2_2" }, { "from": 6, "to": "7" }, { "from": 7, "to": "8" }, { "from": 8, "to": "9" }, { "from": 9, "to": "10" }, { "from": 10, "to": "-2_3" }, { "from": 11, "to": "d_11" }, { "from": "d_11", "to": "-2_4" }, { "from": "d_11", "to": "11" }, { "from": 12, "to": "-2_6" }, { "from": 13, "to": "14" }, { "from": 14, "to": "d_14" }, { "from": "d_14", "to": "3" }, { "from": "d_14", "to": "1" }, { "from": "d_14", "to": "21" }, { "from": 20, "to": "d_20" }, { "from": "d_20", "to": "0" }, { "from": "d_20", "to": "13" }, { "from": 21, "to": "-2_0" }, { "from": 30, "to": "31" }, { "from": 31, "to": "-2_5" }, { "from": 32, "to": "33" }, { "from": 33, "to": "34" }, { "from": 34, "to": "d_34" }, { "from": "d_34", "to": "34" }, { "from": "d_34", "to": "35" }, { "from": 35, "to": "36" }, { "from": 36, "to": "-2_1" }];
var nodeData = [{"key":"-1","name":"Node 1","category":"Start"},{"key":0,"name":"Node 2","category":"DataNode"},{"key":13,"name":"Node 3","category":"DataNode"},{"key":14,"name":"Node 4","category":"DataNode"},{"key":21,"name":"Node 5","category":"DataNode"},{"key":"-2_0","name":"Node 6","category":"END"},{"key":20,"name":"Node 7","category":"DataNode"},{"key":3,"name":"Node 8","category":"DataNode"},{"key":4,"name":"Node 9","category":"DataNode"},{"key":32,"name":"Node 10","category":"DataNode"},{"key":33,"name":"Node 11","category":"DataNode"},{"key":34,"name":"Node 12","category":"DataNode"},{"key":35,"name":"Node 13","category":"DataNode"},{"key":36,"name":"Node 14","category":"DataNode"},{"key":"-2_1","name":"Node 15","category":"END"},{"key":1,"name":"Node 16","category":"DataNode"},{"key":2,"name":"Node 17","category":"DataNode"},{"key":5,"name":"Node 18","category":"DataNode"},{"key":"-2_2","name":"Node 19","category":"END"},{"key":6,"name":"Node 20","category":"DataNode"},{"key":7,"name":"Node 21","category":"DataNode"},{"key":8,"name":"Node 22","category":"DataNode"},{"key":9,"name":"Node 23","category":"DataNode"},{"key":10,"name":"Node 24","category":"DataNode"},{"key":"-2_3","name":"Node 25","category":"END"},{"key":11,"name":"Node 26","category":"DataNode"},{"key":"-2_4","name":"Node 27","category":"END"},{"key":30,"name":"Node 28","category":"DataNode"},{"key":31,"name":"Node 29","category":"DataNode"},{"key":"-2_5","name":"Node 30","category":"END"},{"key":12,"name":"Node 31","category":"DataNode"},{"key":"-2_6","name":"Node 32","category":"END"},{"key":"-2_7","name":"Node 33","category":"END"},{"key":"d_-1","category":"Decision","name":"Node 34"},{"key":"d_0","category":"Decision","name":"Node 35"},{"key":"d_4","category":"Decision","name":"Node 36"},{"key":"d_11","category":"Decision","name":"Node 37"},{"key":"d_14","category":"Decision","name":"Node 38"},{"key":"d_20","category":"Decision","name":"Node 39"},{"key":"d_34","category":"Decision","name":"Node 40"}];


//Define Node, Links, Grid Templates
var defineTemplates = function (){
	//Node Templates
	//Start Node :
	myDiagram.nodeTemplateMap.add("Start", // the name of the Node category
		$Go(go.Node, "Auto",{
				locationSpot: go.Spot.Center,
				deletable: false  // do not allow this node to be removed by the user
			},
			$Go(go.Shape, "Circle",{
				fill: "#FFFFFF",
				strokeWidth: 1,
				stroke: "rgba(0,0,0,0.16)",
				width: 50,
				height: 50
			}),
			$Go(go.TextBlock, "START", {
			    stroke: "rgba(0,0,0,0.54)",
			    font: "bold 10px sans-serif"
			})
		)
	);
	//End Node : 
	myDiagram.nodeTemplateMap.add("END", // the name of the Node category
		$Go(go.Node, "Auto",{
				locationSpot: go.Spot.Center,
				deletable: false  // do not allow this node to be removed by the user
			},
			$Go(go.Shape, "Circle",{
				fill: "#FFFFFF",
				strokeWidth: 1,
				stroke: "rgba(0,0,0,0.16)",
				width: 50,
				height: 50
			}),
			$Go(go.TextBlock, "END", {
			    stroke: "rgba(0,0,0,0.54)",
			    font: "bold 10px sans-serif"
			})
		)
	);
	//Data Node
	myDiagram.nodeTemplateMap.add("DataNode",
		$Go(go.Node, "Position",
          { name: "BODY", width: 202, height: 42 },
          $Go(go.Shape, "RoundedRectangle",
		  { name: "SHAPE", fill: "#FFFFFF", stroke: '#4A90E2', strokeWidth: 1, maxSize: new go.Size(201, 41), minSize: new go.Size(201, 41) }),
          $Go(go.Shape, "RoundedRectangle", { position: new go.Point(0, 0), fill: "#4A90E2", stroke: '#4A90E2', maxSize: new go.Size(10, 41), minSize: new go.Size(10, 41) }),
          $Go(go.Shape, "Rectangle", { position: new go.Point(5, 0), fill: "#4A90E2", stroke: '#4A90E2', maxSize: new go.Size(5, 41), minSize: new go.Size(5, 41) }),
          $Go(go.Panel, "Horizontal",
            { position: new go.Point(15, 1)},
            $Go(go.Panel, "Table",
              {
                  minSize: new go.Size(175, 40),
                  maxSize: new go.Size(175, 40),                  
                  defaultAlignment: go.Spot.Left
              },
              $Go(go.RowColumnDefinition, { column: 1, width: 1 }),
              $Go(go.TextBlock, {
                  font: "12pt  Segoe UI,sans-serif", stroke: "#4A90E2", minSize: new go.Size(150, 15),
                  maxSize: new go.Size(150, 15)
              },
                {
                    row: 0, column: 0,
                    editable: true, isMultiline: false,
                    stretch: go.GraphObject.Horizontal,
                    wrap: go.TextBlock.WrapFit,
                    overflow: go.TextBlock.OverflowEllipsis
                },
                new go.Binding("text", "name").makeTwoWay()),
              $Go(go.TextBlock, "Some Text: ", { font: "9pt  Segoe UI,sans-serif", stroke: "#4A90E2" },
                { row: 1, column: 0, isMultiline: false })
              )  // end Table Panel
          ) // end Horizontal Panel
    ));
	//Decision Node
	myDiagram.nodeTemplateMap.add("Decision",
		$Go(go.Node, "Spot",
			$Go(go.Panel, "Auto",
				$Go(go.Shape, "Diamond",{ width: 50,height: 50,fill: "rgba(74,144,226,0.5)", stroke: "rgba(0,0,0,0.16)" })
			)
		)
	);

	//Link Template
	myDiagram.linkTemplate = $Go(go.Link,{
			selectable: false,      // links cannot be selected by the user
			// curve: go.Link.Bezier,
			routing: go.Link.AvoidsNodes, corner: 10,//curve: go.Link.JumpOver,
			layerName: "Background"  // don't cross in front of any nodes
		},$Go(go.Shape,  // this shape only shows when it isHighlighted
			{ isPanelMain: true, stroke: null, strokeWidth: 5 },
			new go.Binding("stroke", "isHighlighted", function (h) { return h ? "red" : null; }).ofObject()
		),
		$Go(go.Shape,
			// mark each Shape to get the link geometry with isPanelMain: true
			{ isPanelMain: true, stroke: "black", strokeWidth: 1 },
			new go.Binding("stroke", "color")),
		$Go(go.Shape, { toArrow: "Standard" }), 
		{	// a mouse-over highlights the link by changing the first main path shape's stroke:
			mouseEnter: function (e, link) { link.elt(0).stroke = "rgba(0,90,156,0.3)"; },
			mouseLeave: function (e, link) { link.elt(0).stroke = "transparent"; }
		}
	);
	
	//Background Grid Template
	myDiagram.grid =
    $Go(go.Panel, go.Panel.Grid,  // or "Grid"
      { gridCellSize: new go.Size(10, 10) },
      $Go(go.Shape, "LineH", { stroke: "#EFEFEF" }),
      $Go(go.Shape, "LineV", { stroke: "#EFEFEF" })
    );

    //Horizontal Group Node 
	myDiagram.groupTemplateMap.add("horizontalGroup", $Go(go.Group, "Auto",
			{
			    //memberValidation: handleMemberValidation,
			    background: "transparent",
			    ungroupable: true,
			    // highlight when dragging into the Group
			    mouseDragEnter: function (e, grp, prev) { highlightGroup(e, grp, true); },
			    mouseDragLeave: function (e, grp, next) { highlightGroup(e, grp, false); },
			    computesBoundsAfterDrag: true,
			    // when the selection is dropped into a Group, add the selected Parts into that Group;
			    // if it fails, cancel the tool, rolling back any changes
			    mouseDrop: finishDrop,
			    handlesDragDropForMembers: true,  // don't need to define handlers on member Nodes and Links
			    // Groups containing Nodes lay out their members vertically
			    layout:
					$Go(go.GridLayout,
						{
						    wrappingColumn: 0, alignment: go.GridLayout.Position,
						    cellSize: new go.Size(1, 1), spacing: new go.Size(4, 4)
						})
			},
			new go.Binding("background", "isHighlighted", function (h) { return h ? "rgba(255,0,0,0.2)" : "transparent"; }).ofObject(),
			$Go(go.Shape, "Rectangle",
				{ fill: null, stroke: "#4A90E2", strokeWidth: 2 }),
			$Go(go.Panel, "Vertical",  // title above Placeholder
				$Go(go.Panel, "Horizontal",  // button next to TextBlock
					{ stretch: go.GraphObject.Horizontal, background: "#4A90E2" },
					$Go("SubGraphExpanderButton",
						{ alignment: go.Spot.Right, margin: 5 }),
					$Go(go.TextBlock,"New Group",
						{
						    alignment: go.Spot.Left,
						    editable: true,
						    margin: 5,
						    font: "bold 16px sans-serif",
						    opacity: 0.75,
						    stroke: "#FFFFFF"
						},
						new go.Binding("text", "text").makeTwoWay())
				),  // end Horizontal Panel
				$Go(go.Placeholder,
					{ padding: 5, alignment: go.Spot.TopLeft })
			)  // end Vertical Panel
		)  // end Group and call to add to template Map
	);

    //Vertical Group Node 
	myDiagram.groupTemplateMap.add("verticalGroup", $Go(go.Group, "Auto",
			{
			    //memberValidation: handleMemberValidation,
			    background: "transparent",
			    ungroupable: true,
			    // highlight when dragging into the Group
			    mouseDragEnter: function (e, grp, prev) { highlightGroup(e, grp, true); },
			    mouseDragLeave: function (e, grp, next) { highlightGroup(e, grp, false); },
			    computesBoundsAfterDrag: true,
			    // when the selection is dropped into a Group, add the selected Parts into that Group;
			    // if it fails, cancel the tool, rolling back any changes
			    mouseDrop: finishDrop,
			    handlesDragDropForMembers: true,  // don't need to define handlers on member Nodes and Links
			    // Groups containing Nodes lay out their members vertically
			    layout:
					$Go(go.GridLayout,
						{
						    wrappingColumn: 1, alignment: go.GridLayout.Position,
						    cellSize: new go.Size(1, 1), spacing: new go.Size(4, 4)
						})
			},
			new go.Binding("background", "isHighlighted", function (h) { return h ? "rgba(255,0,0,0.2)" : "transparent"; }).ofObject(),
			$Go(go.Shape, "Rectangle",
				{ fill: null, stroke: "#4A90E2", strokeWidth: 2 }),
			$Go(go.Panel, "Vertical",  // title above Placeholder
				$Go(go.Panel, "Horizontal",  // button next to TextBlock
					{ stretch: go.GraphObject.Horizontal, background: "#4A90E2" },
					$Go("SubGraphExpanderButton",
						{ alignment: go.Spot.Right, margin: 5 }),
					$Go(go.TextBlock,"New Group",
						{
						    alignment: go.Spot.Left,
						    editable: true,
						    margin: 5,
						    font: "bold 16px sans-serif",
						    opacity: 0.75,
						    stroke: "#FFFFFF"
						},
						new go.Binding("text", "text").makeTwoWay())
				),  // end Horizontal Panel
				$Go(go.Placeholder,
					{ padding: 5, alignment: go.Spot.TopLeft })
			)  // end Vertical Panel
		) // end Group and call to add to template Map
	);
}

//Add/Remove Node to/from group on drag-drop 
var finishDrop = function(e, grp) {
	var ok = (grp !== null
		? grp.addMembers(grp.diagram.selection, true)
		: e.diagram.commandHandler.addTopLevelParts(e.diagram.selection, true));

	if (!ok) e.diagram.currentTool.doCancel();
}
	
//Flip View between Vertical and Horizontal
var flipView = function () {
	//var oldSkips = myDiagram.skipsUndoManager;
	//myDiagram.skipsUndoManager = true;
	myDiagram.startTransaction("change Layout");//This adds animation for transmision
	
	if (angle == 0) {
		myDiagram.commandHandler.archetypeGroupData.category =  "verticalGroup"; 
		angle = 90;
		$('#flip .fas')[0].classList.remove("fa-arrows-alt-h");
		$('#flip .fas')[0].classList.add("fa-arrows-alt-v");
		myDiagram.commit(function(diag) {
			diag.nodes.each(function(g) {
		        if (g instanceof go.Group) g.layout.wrappingColumn = 1;
		    });
		}); 
		
	} else {
        myDiagram.commandHandler.archetypeGroupData.category =  "horizontalGroup";
		angle = 0;
		$('#flip .fas')[0].classList.remove("fa-arrows-alt-v");
		$('#flip .fas')[0].classList.add("fa-arrows-alt-h");
		myDiagram.commit(function(diag) {
			diag.nodes.each(function(g) {
		      if (g instanceof go.Group) g.layout.wrappingColumn = 0;
		    });
		}); 
	}
	 
	myDiagram.layout.angle = angle; //value can be  0(left to right)/90(top to bottom)/180(right to left)/270(bottom to top)
	
	myDiagram.commitTransaction("change Layout"); 
	myDiagram.undoManager.clear();
	//myDiagram.skipsUndoManager = oldSkips;
	//myDiagram.model.clear();
}	


//Custom Method for mouse Selection which will allow selecting upto 2 nodes
var customMouseSelect = function () {
	var diagram = this.diagram;
	if (diagram === null || !diagram.allowSelect) return;
	var e = diagram.lastInput;
	var count = diagram.selection.count;
	var curobj = diagram.findPartAt(e.documentPoint, false);
	if (curobj !== null) {
		if (count < 2) {  // add the part to the selection
			if (!curobj.isSelected) {
				var part = curobj;
				if (part !== null) part.isSelected = true;
			}
		} else {
			if (!curobj.isSelected) {
				var part = curobj;
				if (part !== null) diagram.select(part);
			}
		}
	} else if (e.left && !(e.control || e.meta) && !e.shift) {
		// left click on background with no modifier: clear selection
		diagram.clearSelection();
	}
}

// When the blob is complete, make an anchor tag for it and use the tag to initiate a download
// Works in:
// * Chrome
// * IE11, Edge
// * Firefox
function myCallback(blob) {
	var url = window.URL.createObjectURL(blob);
	var filename = "Task Map.svg";

	var a = document.createElement("a");
	a.style = "display: none";
	a.href = url;
	a.download = filename;

	// IE 11
	if (window.navigator.msSaveBlob !== undefined) {
		window.navigator.msSaveBlob(blob, filename);
		return;
	}

	document.body.appendChild(a);
	requestAnimationFrame(function () {
		a.click();
		window.URL.revokeObjectURL(url);
		document.body.removeChild(a);
	});
}
//Download as SVG
function downloadSvg() {
	var svg = myDiagram.makeSvg({ scale: 1, background: "white" });
	var svgstr = new XMLSerializer().serializeToString(svg);
	var blob = new Blob([svgstr], { type: "image/svg+xml" });
	myCallback(blob);
}
//Download as PNG
var downloadPng = function () {
	startLoader();
	setTimeout(() => {
		var imageData = myDiagram.makeImage({
			scale: 1,
			type: "image/png",
			background: "white"
		});
		var aTag = document.createElement('a');
		aTag.setAttribute('href', imageData.src);
		aTag.setAttribute('download', 'Task Map.png');
		aTag.style.display = 'none';
		document.body.appendChild(aTag);
		aTag.click();
		document.body.removeChild(aTag);
		stopLoader();
	}, 100);
}

//Download as JPEG
var downloadJPEG = function () {
	startLoader();
	setTimeout(() => {
		var imageData = myDiagram.makeImage({
			scale: 1,
			type: "image/jpeg",
			background: "white"
		});
		var aTag = document.createElement('a');
		aTag.setAttribute('href', imageData.src);
		aTag.setAttribute('download', 'Task Map.jpeg');
		aTag.style.display = 'none';
		document.body.appendChild(aTag);
		aTag.click();
		document.body.removeChild(aTag);
		stopLoader();
	}, 100);
}

//Page Loader
var startLoader = function () {
	$('#spinner')[0].style.display = "block";
}
var stopLoader = function () {
	$('#spinner')[0].style.display = "none";

}

// this function is used to highlight a Group that the selection may be dropped into
var highlightGroup = function (e, grp, show) {
	if (!grp) return;
	e.handled = true;

	if (show) {
		// cannot depend on the grp.diagram.selection in the case of external drag-and-drops;
		// instead depend on the DraggingTool.draggedParts or .copiedParts
		var tool = grp.diagram.toolManager.draggingTool;
		var map = tool.draggedParts || tool.copiedParts;  // this is a Map
		// now we can check to see if the Group will accept membership of the dragged Parts
		if (grp.canAddMembers(map.toKeySet())) {
			grp.isHighlighted = true;
			return;
		}
	}
	grp.isHighlighted = false;
}

//Export JSON
var convertToJson = function () {
    //savePointData();
    var jsonString = myDiagram.model.toJson();
    myDiagram.isModified = false;

    //var jsonString = JSON.stringify(myDiagram.model.toJson());
    var aTag = document.createElement('a');
    aTag.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(jsonString));
    aTag.setAttribute('download', 'graph.json');

    aTag.style.display = 'none';
    document.body.appendChild(aTag);

    aTag.click();
    document.body.removeChild(aTag);
}



//Import JSON
var openBrowseBox = function () {
    $('#importJsonInput')[0].click();
}
var importFileSelected = function (event) {
    var reader = new FileReader();
    reader.onload = onReaderLoad;
    reader.readAsText(event.target.files[0]);
}
var onReaderLoad = function (event) {
    var importedJson = JSON.parse(event.target.result);
	//changeData(importedJson);
    myDiagram.model = go.Model.fromJson(importedJson);
	
}

var init = function () {
	document.getElementById("importJsonInput").addEventListener("change", importFileSelected);
	$Go = go.GraphObject.make;  // for conciseness in defining templates
	
	myDiagram = $Go(go.Diagram, "myDiagramDiv",{
		//contentAlignment: go.Spot.Center,	
        //initialDocumentSpot: go.Spot.Center,
        //initialViewportSpot: go.Spot.Center,
		mouseDrop: function (e) { finishDrop(e, null); },// finishDrop will be called when a drag-drop occurs in the Diagram's background
		layout: $Go(go.TreeLayout,{
			"layerSpacing":40, // Spacing between the Layers
			"nodeSpacing":40,// Spacing between the Columns
			"setsPortSpot":go.Link.fromSpot,
			//"setsChildPortSpot":go.Link.toSpot,
			"angle":angle	//value can be  0(left to right)/90(top to bottom)/180(right to left)/270(bottom to top)
		}),
		"commandHandler.archetypeGroupData": { isGroup: true, category: "verticalGroup" },	// Allows to group selected nodes to group on "ctrl + G"
		"undoManager.isEnabled": true, // enable Ctrl-Z to undo and Ctrl-Y to redo
		"panningTool.isEnabled": false,
		"dragSelectingTool.isEnabled": true,
		"grid.visible":true,
		//initialAutoScale: go.Diagram.UniformToFill,
	});
	go.AnimationManager.isEnabled=false;
	myDiagram.model = new go.GraphLinksModel(nodeData,nodeLinks);
	
	
	zoomSlider = new ZoomSlider(myDiagram);
	
	//Define Node, Links, Grid Templates
	defineTemplates();
	
	// Allow selection upto 2 node by Overriding the clickSelectingTool's standardMouseSelect
	myDiagram.toolManager.clickSelectingTool.standardMouseSelect = customMouseSelect;
	
}

Any layout for which you do not actually change the value of one of its properties, such as GridLayout.wrappingColumn, does not become invalidated, so such layouts will not need to be performed again.

If you want to blindly force each Layout to be performed again, just call Layout.invalidateLayout on each one.

Hi

We have two Group Templates
“HorizontalGroup”:

		    $Go(go.Group, "Auto",{background: "transparent",
		    ungroupable: true,
		   
		    mouseDragEnter: function (e, grp, prev) { highlightGroup(e, grp, true); },
		    mouseDragLeave: function (e, grp, next) { highlightGroup(e, grp, false); },
		    computesBoundsAfterDrag: true,
		    mouseDrop: finishDrop,
		    handlesDragDropForMembers: true,  
		    layout:
				$Go(go.GridLayout,
					{
					    wrappingColumn: 0, alignment: go.GridLayout.Position,
					    cellSize: new go.Size(1, 1), spacing: new go.Size(4, 4)
					})
		},
		new go.Binding("background", "isHighlighted", function (h) { return h ? "rgba(255,0,0,0.2)" : "transparent"; }).ofObject(),
		$Go(go.Shape, "Rectangle",
			{ fill: null, stroke: "#4A90E2", strokeWidth: 2 }),
		$Go(go.Panel, "Vertical",  // title above Placeholder
			$Go(go.Panel, "Horizontal",  // button next to TextBlock
				{ stretch: go.GraphObject.Horizontal, background: "#4A90E2" },
				$Go("SubGraphExpanderButton",
					{ alignment: go.Spot.Right, margin: 5 }),
				$Go(go.TextBlock,"New Group",
					{
					    alignment: go.Spot.Left,
					    editable: true,
					    margin: 5,
					    font: "bold 16px sans-serif",
					    opacity: 0.75,
					    stroke: "#FFFFFF"
					},
					new go.Binding("text", "text").makeTwoWay())
			),  // end Horizontal Panel
			$Go(go.Placeholder,
				{ padding: 5, alignment: go.Spot.TopLeft })
		)  // end Vertical Panel
	)

And “verticalGroup”:

		     $Go(go.Group, "Auto",{background: "transparent",
		    ungroupable: true,mouseDragEnter: function (e, grp, prev) { highlightGroup(e, grp, true); },
		    mouseDragLeave: function (e, grp, next) { highlightGroup(e, grp, false); },
		    computesBoundsAfterDrag: true,
		    mouseDrop: finishDrop,
		    handlesDragDropForMembers: true,  
		    layout:
				$Go(go.GridLayout,
					{
					    wrappingColumn: 0, alignment: go.GridLayout.Position,
					    cellSize: new go.Size(1, 1), spacing: new go.Size(4, 4)
					})
		},
		new go.Binding("background", "isHighlighted", function (h) { return h ? "rgba(255,0,0,0.2)" : "transparent"; }).ofObject(),
		$Go(go.Shape, "Rectangle",
			{ fill: null, stroke: "#4A90E2", strokeWidth: 2 }),
		$Go(go.Panel, "Vertical",  // title above Placeholder
			$Go(go.Panel, "Horizontal",  // button next to TextBlock
				{ stretch: go.GraphObject.Horizontal, background: "#4A90E2" },
				$Go("SubGraphExpanderButton",
					{ alignment: go.Spot.Right, margin: 5 }),
				$Go(go.TextBlock,"New Group",
					{
					    alignment: go.Spot.Left,
					    editable: true,
					    margin: 5,
					    font: "bold 16px sans-serif",
					    opacity: 0.75,
					    stroke: "#FFFFFF"
					},
					new go.Binding("text", "text").makeTwoWay())
			),  // end Horizontal Panel
			$Go(go.Placeholder,
				{ padding: 5, alignment: go.Spot.TopLeft })
		)  // end Vertical Panel
	)

And we want to toggle the template of each group on button click:
And Referring to :
https://gojs.net/latest/intro/templateMaps.html
I have written the following code:

myDiagram.findTopLevelGroups().each(function(node){
  var diagram = node.diagram;
  diagram.startTransaction("changeCategory");
   var cat = diagram.model.getCategoryForNodeData(node.data);
  if (cat === "verticalGroup")
    cat = "horizontalGroup";
  else
    cat = "verticalGroup";
  diagram.model.setCategoryForNodeData(node.data, cat);
  diagram.commitTransaction("changeCategory");
})

but template is not getting changed.
Can you please guide were are we going wrong.

Your code looks OK, from what I can see. Are you sure that the corresponding template name is exactly the same? EDIT: and that the templates are actually different? Upon a quick review, I don’t see any difference between the two templates.

The only difference in that two Template was in horizontal group the wrappingColumn value is 0 and in vertical group it is 1.

I have also crossed verified both the template names are right, to be more sure I have copied and pasted it from template map declaration itself.

Well, the value of GridLayout.wrappingColumn is zero in both cases, above.

If the templates are structurally the same and if there aren’t too many differences between the two templates in their property values I would highly recommend that you just use one template with Bindings to produce the different property values. In this case if the only difference is in the value of the Group.layout, then with a change to the data, replacing { category: "...Group" } with { vertical: true } or { vertical: false }, you could use:

    new go.Binding("layout", "vertical", function(v) {
      return $(go.GridLayout, { wrappingColumn: (v ? 1 : 0), . . . });
    }),

And your code, instead of calling get/setCategoryForNodeData, would just call:

myDiagram.commit(function(diag) {
  diag.findTopLevelGroups().each(function(g) {
      diag.model.set(g.data, "vertical", !g.data.vertical);
    });
}, "toggled layout direction");

Note also that your original code had a bug that was executing a transaction within a loop, which is generally not what you want.

In this case if we add/create a new group how would we able to set vertical property.

Just make sure it has all of the data properties that the group template is expecting.