CatarinaRuna
CatarinaRuna

Reputation: 569

number string NaN error correction workaround

I have a member variable total explicitely of type number (in a strict Angular app) which is initialized in the constructor but then shows as type any in the drawSlices() method, resulting in my tooltip label showing NaN.

export class SomeComponent implements OnInit {
         
  total: number;
  dataSource: Item[];

  constructor(private dataService: DataService) {
    this.dataSource = this.dataService.getData();
    this.total = this.dataSource.reduce((sum, element) => sum += element.abs, 0);
  }
    
  drawSlices() {   
    const mousemove = function (event, d) {
      const percent = (Math.abs(d.data.abs / this.total) * 100).toFixed(2) + "%";
      tooltip
        .style("left", (event.pageX) + "px")
        .style("top", (event.pageY - 80) + "px")
        .style("display", "block")
        .style("opacity", 1)
        .style("height", "40px");
      tooltip.html(`name: ${d.data.name}<br>value: ${d.data.value}<br>share: ${percent}`);
    }
}

I have tried forcing the type, and similar workarounds, to no avail...

let t: number = this.total;
const percent = (Math.abs(d.data.abs / t) * 100).toFixed(2) + "%";

How do I fix this to get a number followed by %?

Upvotes: 1

Views: 242

Answers (1)

Nayak
Nayak

Reputation: 772

The issue is due to the scope of 'this' in mousemove function. Convert the normal function to an ES6 (arrow) function and you should be good to go. It will get the scope of the component, and would return the correct 'total' variable.

const mousemove = (event, d) => {
  const percent = (Math.abs(d.data.abs / this.total) * 100).toFixed(2) + "%";
  ...
}

Put a debug point for the line you are using this.total and see the value assinged to it.

Upvotes: 2

Related Questions