Trying to build an application with interactive charts in Angular using SVG, it became clear that d3.js could be a valuable tool. However, the initial attempts had to be refined since a basic d3.select(..).on(click) approach was not functioning as expected. Additionally, navigating TypeScript posed a challenge due to limited experience.
See the HTML snippet below:
<button id="button1" class="btn btn-success" (click)="onButton1()">
Button 1</button>
<button id="button2" class="btn btn-danger">Button 2</button>
<br>
<svg width="1000" height="500" style="background-color: aqua"></svg>
As for the TypeScript code:
import { Component, OnInit } from '@angular/core';
import * as d3 from "d3";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
user_id:number = 1;
ngOnInit(){
d3.select("#button2")
.on("click", this.onButton2);
}
onButton1(){
console.log("button 1 was clicked, user_id: " + this.user_id);
}
onButton2(){
console.log("button 2 was clicked, user_id: " + this.user_id);
}
}
The console output displays:
- Angular is running in the development mode. Call enableProdMode() to enable the production mode.
- app.component.ts:22 button 1 was clicked, user_id: 1
- app.component.ts:26 button 2 was clicked, user_id: undefined
An issue arises where the method bound through d3.select... fails to access the class field. What could potentially cause this problem?