tomwanzek/d3-ng2-demo

Question: understanding path generator function syntax

Closed this issue · 1 comments

Hi there,

I am attempting to implement a brush-able line chart within an Angular 4 app using the D3 service. While I'm quite familiar with D3 syntax in vanilla JS, I'm somewhat new to TypeScript and Angular, so I'm having a bit of trouble understanding how to troubleshoot some of the errors I'm seeing.

Outside of a TypeScript context, I would do something like the following:

let data = [
    {
        x: 0,
        y: 3    
    },{
        x: 1,
        y: 16    
    },{
        x: 2,
        y: 21    
    },{
        x: 3,
        y: 24    
    }
];

let line = d3.line()
    .x(function(d) { return x(d.x); })
    .y(function(d) { return y(d.y); });

focus.append("path")
   .datum(data)
   .attr("class", "line")
   .attr("d", line);

In my Angular component, I am doing something like this:

import { D3Service, D3, Selection, Line, CurveGenerator, Path } from 'd3-ng2-service';
import { Datum } from '../data-defs';

let d3ParentElement: Selection<HTMLElement, any, null, undefined>; 
let d3Svg: Selection<SVGSVGElement, any, null, undefined>;
let d3G: Selection<SVGGElement, any, null, undefined>;
let line: Line<Datum>;
let data: Datum[] = [
    {
        x: 0,
        y: 3    
    },{
        x: 1,
        y: 16    
    },{
        x: 2,
        y: 21    
    },{
        x: 3,
        y: 24    
    }
];

d3ParentElement = d3.select(this.parentNativeElement); // <-- use the D3 select method
d3Svg = d3ParentElement.select<SVGSVGElement>('svg');
let focus = d3Svg.append<SVGGElement>("g")
                  .attr("class", "focus");

line = d3.line()
    .x(function(d) { return x(d.x); })
    .y(function(d) { return y(d.y); });

focus.append<SVGPathElement>("path")
    .datum(data)
    .attr("class", "line")
    .attr("d",line);

With this syntax, I get an error Argument of type XXX is not assignable to parameter of type XXX, on the line where the path string should be passed to the d attribute of the path. Is there an additional method for outputting the path string from the line generator that I am missing?

Obviously I am omitting quite a bit of code from the component, but since I am not getting an error from the Line accessor functions, and only from invoking the path string from a selection, I'm guessing that's where the problem is.

Apologies in advance if there is something glaringly obvious with my approach. I tried to glean as much as I could from the examples, but the demo doesn't include use of a path generator function like d3.line in an SVG context.

For "How-to" questions, please use Stackoverflow. Thanks for understanding. 😄