Why is my D3 svg not showing on the screen?

Issue

Here is my code! I am using angular and d3 library to make a simple shape but nothing shows up on the screen.

pie-chart TS File:

@Component({
  selector: 'pie-chart',
  templateUrl: './pie-chart.component.html',
  styleUrls: ['./pie-chart.component.css'],
})

export class PieChartComponent {
  svg = d3
    .select('#canvasarea')
    .append('svg')
    .attr('width', 400)
    .attr('height', 100);

  circle = this.svg
    .append('circle')
    .attr('cx', 200)
    .attr('cy', 200)
    .attr('r', 50)
    .attr('fill', 'blue');
}

pie-chart HTML File:

<div id="canvasarea"></div>

app-component.html:

<pie-chart></pie-chart>

Solution

As mention above indeed you need to add a radius with r attribute. And you also need the view to have been rendered in your angular component to add the svg and do the operation on it

import { AfterViewInit, Component } from '@angular/core';
import * as d3 from 'd3';

@Component({
  selector: 'pie-chart',
  templateUrl: './pie-chart.component.html',
  styleUrls: ['./pie-chart.component.css'],
})
export class PieChartComponent implements AfterViewInit {
  public svg: any = null;

  constructor() { }

  ngAfterViewInit(): void {
    this.svg = d3
      .select('#canvasarea')
      .append('svg')
      .attr('width', 400)
      .attr('height', 100);

    this.svg
      .append('circle')
      .attr('cx', 50)
      .attr('cy', 50)
      .attr('r', 20)
      .style('fill', 'blue');
  }
}

Answered By – Ninii

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.