d3 with Angular 2 - 无法读取属性'style'的null

时间:2016-07-04 19:46:28

标签: javascript angularjs d3.js

我正在尝试将d3.js与Angular 2一起使用。我在自己的指令中使用了d3:

import * as angular from '@angular/core';
import { Directive, OnChanges, OnInit, ViewContainerRef, Attribute } from '@angular/core';
import { Inject } from '@angular/core';
import * as d3 from 'd3/d3';

@Directive({
    selector: 'life-cycle-visual',
    properties: ['data']
})

export class LifeCycleVisual implements OnChanges {

    public data: number[];
    public divs: any;

    constructor(
        @Inject(ViewContainerRef) viewContainerRef: ViewContainerRef,
        @Attribute('width') width: string,
        @Attribute('height') height: string) {

        var el:any    = viewContainerRef.element.nativeElement;
        var graph:any = d3.select(el);
        console.log(graph);

        this.divs = graph.
              append('div').
              attr({
                'class': 'chart'
              }).
              style({
                'width':  width  + 'px',
                'height': height + 'px',
              }).
              selectAll('div');
    }

    render(newValue) {
    if (!newValue) return;

    this.divs.data(newValue).enter().append('div')
      .transition().ease('elastic')
      .style('width', d => d + '%')
      .text(d => d + '%');

  }

  onChanges() {
    this.render(this.data);
  }
}

我在控制台中收到此错误:

TypeError: Cannot read property 'style' of null

现在console.log确保graph变量正常并且d3正确选择元素,但由于某种原因我仍然会收到此错误。

有什么想法吗?

0 个答案:

没有答案