angular2 d3:将 d3 svg 鼠标位置更新为组件属性

bee*_*est 0 svg d3.js angular

D3 用于svgangular2组件中生成 a 。如何从 svg 事件更新属性xy组件mousemove

export class AxisComponent implements OnInit {
    x:number;
    y:number;     

    ngOnInit() {
        var svgWidth=400;
        var svgHeight=400;
        var margin = {top:25, right:25, bottom:50, left:50};
        var width = svgWidth - margin.left - margin.right;
        var height = svgHeight - margin.top - margin.bottom;

        var svg = d3.select('#container').append('svg')
            .attr('width', svgWidth)
            .attr('height',svgHeight)
            .style('border', '2px solid');

        svg.on("mousemove", function(){
            var xy = d3.mouse(this);

            this.x = xy[0]; 
            this.y = xy[0];
        });
}
Run Code Online (Sandbox Code Playgroud)

mousemove事件访问时出错:

在此处输入图片说明

yur*_*zui 5

我怀疑它应该是:

svg.on("mousemove", () => {
   var xy = d3.mouse(svg); // or d3.mouse(d3.event.currentTarget);
   this.x = xy[0]; 
   this.y = xy[0];
Run Code Online (Sandbox Code Playgroud)

或者这样:

let self = this;
svg.on("mousemove", function(){
  var xy = d3.mouse(this);

  self.x = xy[0]; 
  self.y = xy[0];
});
Run Code Online (Sandbox Code Playgroud)