I am working with Angular 2 and D3.js to display a red rectangle.
The issue arises when I attempt to define styles within the style.css file. You can view the problem on this plunkr
If I try to place my styles in the component using styles: []
, it fails to render as expected. Take a look at the example on this plunkr
Is there a way to make it work when utilizing styles: []
within the component? Any suggestions would be appreciated.
UPDATE: @micronyks has offered a solution, but it essentially makes the component's styles global, which is similar to defining them in the style.css file. As shown in this plunkr, conflicting component styles prevent displaying both green and red rectangles simultaneously.
UPDATE 2: @Günter's method successfully resolves this issue!! It's worth noting that Günter's approach requires at least Angular beta 10 (while my previous examples were based on Angular beta 8). To see a functional demo showcasing both green and one red rectangle using Angular beta 12, visit here.
import {Component} from 'angular2/core'
@Component({
selector: 'my-app',
providers: [],
styles: [`
/*this does not work*/
.bar {
fill: red;
}
`],
template: `
<div>
<svg class="chart"></svg>
</div>
`,
directives: []
})
export class App {
constructor() {}
ngOnInit() {
this.draw();
}
draw() {
let data = [{name: 'A', value: 1}];
let width = 400, height = 200;
let x = d3.scale.ordinal().rangeRoundBands([0, width]);
let y = d3.scale.linear().range([height, 0]);
let chart = d3.select(".chart")
.attr("width", width)
.attr("height", height)
.append("g");
x.domain(data.map(function(d) { return d.name; }));
y.domain([0, d3.max(data, function(d) { return d.value; })]);
chart.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.attr("width", x.rangeBand());
}
}