D3, Angular component passing in variable

386 views Asked by At

I have a plunker here - https://plnkr.co/edit/yGugULSedKD3EV073YP4?p=preview

This question follows on from my question here - D3 - Passing variable to x scale

I'm trying to create a stacked bar chart component in Angular

To make it reusebable I need to pass in variables to the component.

I need to pass variables to the xscale function and to the x attr of the bars

In the plunker I'm passing in the string 'date'

This work in the x attr of the bars

private xAxisData = 'date'

.attr("x", (d) => {
 let xAxisData = d.data[this.xAxisData];
 return this.x(xAxisData)
 //instead of 
 //return x(d.data.date)
})

It doesn't work in the xscale function.

private xAxisData = 'date'

this.x = d3.scaleBand()
    .domain(this.data.map((d) => {
      //This doesn't work 
      //return d[xAxisValue];
        return d.date;
    }))
    .range([0, this.width])
    .padding(0.1);  

I the pervious question I linked, passing the variable in the x scale works but it doesn't work in Angular.

Can anyone see how to fix this.

1

There are 1 answers

0
aCiD On BEST ANSWER

Seems I fixed it - https://plnkr.co/edit/qeXnuTjTrQwl89Y38840?p=info

Save the component instance first.

let self=this;

Then use it in the lambda for the xscale domain.

  this.x = d3.scaleBand()
        .domain(this.data.map((d) => {
          return d[self.xAxisData];
            //return d.date;
        }))
        .range([0, this.width])
        .padding(0.1);

Its about variable scopes. In the earlier code, 'xAxisData' was not present in the scope of lambda for domain of xscale.