Search code examples
javascripthrefgojs

How to add href inside node in Gojs?


I created a diagram with GoJS. I need that every node will contain a href.

var template = GO(go.Node, "Auto", {
        desiredSize: new go.Size(width, height)
    },
    GO(go.Shape, shapeMap.getValue(shape), new go.Binding("fill", "fill")),
    GO(go.TextBlock, {
        textAlign: 'center',
        margin: 4
    }, new go.Binding("stroke", "color"), new go.Binding("text", "text")));

var node = {
    key: src,
    color: textColor,
    fill: backgroundColor,
    category: shape,
    text: "www.google.com"
};

diagram.model.addNodeData(node);

I tried to insert a Html content.

var node = {
    key: src,
    color: textColor,
    fill: backgroundColor,
    category: shape,
    text: <a href='www.google.com'>href</a>
};

But it's not working. How can I do that?


Solution

  • A TextBlock does not render HTML, but just a string as a block of text.

    If you put the URL in your node data, you can declare a GraphObject.click event handler that opens a window.

    GO(go.Node, . . .
      {
        click: function(e, obj) {
            window.open("http://" + encodeURIComponent(obj.part.data.url));
          }
      },
      . . .
      GO(go.TextBlock,
        { textAlign: "center", margin: 4 },
        new go.Binding("stroke", "color"),
        new go.Binding("text", "url"))
      ),
      . . .
    )
    

    This is for node data such as:

    { url: "www.example.com" }
    

    You can use a conversion function on the TextBlock.text binding to show a different string than the data.url property value.

    It is also demonstrated by the sample at http://gojs.net/latest/samples/euler.html