0

I have appended 5 rects on my SVG and tried to bind mouseOver in each element which will alter their color fill individually when hovered.

Problem:
How do you call this.d3 within calling element's function?

I tried this.d3.select(this) but it will of course reference the current Angular Component

I tried this.d3.select(this) but this keyword references the current Angular Component

As mentioned by @yurzui, this doesn't refer to the Angular Component but instead refers to the element itself.

private d3: D3;

foo(): void {
    let x = 0;
    for (let i = 0; i < 5; i ++) {
        this.svg.append('rect')
        .attr('x', x)
        .attr('y', 100)
        .styles({
            'width' : 100,
            'height' : 100,
            'fill' : '#2196F3'
        })
        .on('mouseover', this.bar);

        x += 110;
    }
}

bar(d, i) {
    // Change the color of the hovered rect
    // this is referencing the current element
    // unable to call this.d3 since this is referencing the element
    this.d3.select(this)
    .attr('fill', 'red');
}
Michael 'Maik' Ardan
  • 4,213
  • 9
  • 37
  • 60
  • Are you sure it will refer to angular component? You can also use `d3.event.currentTarget` to access element – yurzui Mar 07 '18 at 09:08
  • Hi @yurzui, sorry. I edited the question for other's reference. `this` keyword refers to the active angular component – Michael 'Maik' Ardan Mar 07 '18 at 09:22
  • Can you setup plunker? – yurzui Mar 07 '18 at 09:43
  • @yurzui, I'm trying but I can't seem to setup d3 in Plunkr. Anyway, tried a few testing and found that you were right. `this` actually references the current element. My problem now is how will I be able to call `d3` that I have declared in my component. *Edited the question* – Michael 'Maik' Ardan Mar 07 '18 at 10:27

0 Answers0