1

I have a demo here

It's a simple D3 bar chart in an angular app.

I want to check if the x-axis text has 'Feb' in it.

If it does I want to change it style.

In the exmaple here it is changing the color in the y-axis.

How check the axis has a particular name and style it.

private accessTicks(){
    d3.select(".x-axis")
      .selectAll('g')
      .each(function(d) {
        d3.select("text")
        .filter(() => {
          return d3.select(this).text() === 'Feb'
        })
        .attr("fill", 'red'); 

      });
  }  
altocumulus
  • 21,179
  • 13
  • 61
  • 84
cdmt
  • 685
  • 4
  • 12
  • 23

1 Answers1

3

The obvious problem here is that this inside an arrow function doesn't mean the DOM element. As a solution you can use the third and second arguments combined or, easier, just the first one, which is the datum:

 .filter((d) => { 
    return d === 'Feb'
 })  

Also, you can select all the texts at once (no need for those four selection methods you have). So, it becomes:

private accessTicks() {
  d3.selectAll(".x-axis text")
    .filter(d => d === 'Feb')
    .attr("fill", 'red');
}
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
  • It is possible to add a class to the `line` is above this text element that is selected here – cdmt Jan 19 '20 at 11:33
  • @cdmt yes, after you have selected the text the line is just `this.previousSibling`. You can also just get the line directly, with `d3.selectAll(".x-axis text")` and the subsequent filter. – Gerardo Furtado Jan 19 '20 at 11:46
  • I had tried `previousSibling` but I get an error - `Property 'previousSibling' does not exist on type 'StackedChartCompoent'.` I have updated the question with how I'm trying to do it. – cdmt Jan 19 '20 at 12:06
  • 1
    @cdmt please do not update your question, because it becomes a mess: I already answered what you asked. If you have a new issue, post it as a new question. – Gerardo Furtado Jan 19 '20 at 13:12