D3.js elements not in DOM on second page view

I have created a simple Ionic app for testing the integration of d3.js. It can be found here:

I did the integration as follows:

  1. Create an app with side navigation and a single page (home.html)
  2. Add home.html to the menu.
  3. Load d3.js in index.html:
    <script src="https://d3js.org/d3.v4.min.js"></script>
  4. Add <div id="chart"></div> to home.html
  5. Create the chart in ngAfterViewInit() in home.ts

The home template is defined as follows:

<ion-header>
  <ion-navbar>
    <button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  The world is your oyster.
  <p>
    If you get lost, the <a href="http://ionicframework.com/docs/v2">docs</a> will be your guide.
  </p>
  <div id="chart"></div>
  <p>After</p>
</ion-content>

The chart creation is implemented as follows:

  ngAfterViewInit() {
    this.createChart();
  }

  createChart() {
    var chart = d3.select("#chart").append("svg")
      .attr("width", 100)
      .attr("height", 100)
      .append("g");

    var rows = [
      {x: 1, y: 1},
      {x: 2, y: 2},
      {x: 3, y: 3},
    ];

    var xScale = d3.scaleLinear()
            .range([0, 100])
            .domain([1, 3]);
    var yScale = d3.scaleLinear()
            .range([100, 0])
            .domain([1, 3]);

    chart.selectAll(".dot")
      .data(rows)
      .enter().append("circle")
      .attr("class", "dot")
      .attr("cx", (row) => { return xScale(row.x) })
      .attr("cy", (row) => { return yScale(row.y) })
      .attr("r", 3.5);
  }

When starting the app, the chart is displayed as intended. But when (re-)opening the page from the side menu, the chart is not there. When inspecting the TS/DOM in Google Chrome, I can observe the following behaviour when re-opening:

  • ngAfterViewInit() gets called and in turn calls ‘createChart()’
  • The previously created SVG elements are still there
  • A second SVG element is created and filled by createChart()

After ngAfterViewInit() the created SVG is gone. It seems that the DOM is replaced with the empty template.

So my questions are:

  • What goes wrong here? What should I know?
  • How can I fix that?

Edit: I also posted this on stackoverflow.

Hi wberger,
Did you find any solution on this issue because i am also facing same problem. If you have found any solution for this let me now.

Hi I answered this here:

I hope this helps!

Thanks I will try it out