Home > Mobile >  How to use D3-GraphViz in Javascript with an Angular template
How to use D3-GraphViz in Javascript with an Angular template

Time:07-12

I'm trying to use d3-graphviz as described here in an angular template, such as this one. The demo on the d3-graphviz site instructs me to put the following code in the index.html file

 <!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="//d3js.org/d3.v5.min.js"></script>
<script src="https://unpkg.com/@hpcc-js/[email protected]/dist/index.min.js"></script>
<script src="https://unpkg.com/[email protected]/build/d3-graphviz.js"></script>
<div id="graph" style="text-align: center;"></div>
<script>

d3.select("#graph").graphviz()
    .renderDot('digraph  {a -> b}');

</script>

However, when I put this in the dashboard.component.html file (which is where I want the result to show), I get the following error in the console

ERROR TypeError: pe.select is not a function
at h.ngOnInit (383.js:1:105583)
at Ki (main.js:1:183802)
at qn (main.js:1:183633)
at ao (main.js:1:183353)
at Ha (main.js:1:210163)
at Gv (main.js:1:210461)
at Ha (main.js:1:210486)
at $v (main.js:1:217064)
at wv (main.js:1:210896)
at Ha (main.js:1:210907)

Any help with this would be appreciated. I can provide more information if needed

CodePudding user response:

It's because by the time you run your script d3 is not loaded yet.

Put d3 scripts in head tag and then run the script like this:

document.addEventListener("DOMContentLoaded", function(event) { 
  d3.select("#graph").graphviz()
    .renderDot('digraph  {a -> b}');
});

This way the script will execute after all script links are loaded.

  • Related