Я строю серию графиков d3 в угловых 5. Я строю один и тот же d3 несколько раз с разными данными каждый раз, поэтому я назначаю переменную для id. Проблема в том, что идентификатор назначается в то время, когда d3.select () ищет его, поэтому он еще не назначен, и я получаю сообщение об ошибке Невозможно прочитать свойство 'getAttribute' с нулевым значением
Как я могу присвоить 'id' моей предполагаемой 'svg' переменную из тех же данных, которые я использую для ее построения? Прямо сейчас все это находится в функции onInit в моем компоненте.
В моих осадках.component.ts:
this.input_id += this.data.id
var svg = d3.select("#"+this.input_id)
Мой HTML выглядит так:
<svg width="180" height="100"[attr.id]="input_id" > </svg>
Весь осадок.component.ts для справки:
import { Component, OnInit, Input } from '@angular/core';
import { DataService } from '../data.service';
import { Http } from '@angular/http';
import * as d3 from 'd3';
@Component({
selector: 'app-precipitation',
templateUrl: './precipitation.component.html',
styleUrls: ['./precipitation.component.css']
})
export class PrecipitationComponent implements OnInit {
@Input() site1;
constructor(private _dataService: DataService, private http: Http) { }
date: Date;
dates: any;
value: Number;
eachobj: any;
data: any;
values: any;
average: any;
myClasses: any;
name: any;
input_id;
ngOnInit() {
this.name = this.site1.name;
var parse = d3.timeParse("%Y-%m-%d")
this.data = this.site1
this.input_id = ""
this.input_id += "precipitation"
this.input_id += this.data.id
this.dates = Object.keys(this.data.historical_data)
this.values = Object.values(this.data.historical_data)
this.values.forEach((obj, i) => obj.date = this.dates[i]);
this.data = this.values
var svg = d3.select("#"+this.input_id)
// svg = svg.select("." + this.name)
var margin = { top: 20, right: 20, bottom: 30, left: 0 },
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
barPadding = 5,
barWidth = (width / this.data.length);
var last = this.data[0].date
var first = this.data[(this.data.length) - 1].date
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1)
.domain(this.data.map(function (d) { return d['date']; }));
var y = d3.scaleLinear().rangeRound([height, 0])
.domain(<[Date, Date]>d3.extent(this.data, function (d) { return d['precipitation']; }));
g.selectAll(".bar")
.data(this.data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function (d) { return x(d['date']); })
.attr("y", function (d) { return y(d['precipitation']); })
.attr("width", barWidth - barPadding)
.attr("height", function (d) { return height - y(d['precipitation']); });
var line = d3.line()
.x(function (d) { return x(d['date']); })
.y(function (d) { return y(d['precipitation']); });
svg.append('g')
.attr("class", "axis--x")
.append("text")
.attr("fill", "#000")
.attr("x", (width / 2) - 80)
.attr("y", height + 40)
.text(first)
.style("font-size", "09")
.style("font-family", "Roboto")
.style('fill', '#5a5a5a');
svg.append('g')
.attr("class", "axis--x")
.append("text")
.attr("fill", "#000")
.attr("x", (width / 2) + 45)
.attr("y", height + 40)
.text(last)
.style("font-size", "09")
.style("font-family", "Roboto")
.style('fill', '#5a5a5a');
svg.append("path")
.data(this.data)
.attr("class", "line")
.attr("d", line);
}
}
Кстати, я получаю данные через родительский компонент:
<app-precipitation [site1]="site"></app-precipitation>