How to use 'this' in Angular with D3?

前端 未结 2 821
轻奢々
轻奢々 2020-11-28 14:15

Tldr; How do I deal with this in reference to a D3 object when Angular binds this to the class (component/service)?


相关标签:
2条回答
  • 2020-11-28 14:56

    In most of D3 methods, this refers to the DOM element, and it is the most simple way to get the element. However, you're facing some problems using this in your angular code.

    The good news is that there is an idiomatic way to get the current DOM element without relying on this (and without relying on d3.event as well): using the second and the third arguments combined. This is quite useful in situations where you cannot use this, like your situation right now or when using an arrow function, for instance.

    That alternative to this is extensively documented on the API. For most D3 methods, you can read that the method is...

    ... being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). (both emphases mine)

    So, in a common D3 code, you can get the DOM element using:

    .on("whatever", function(){
        d3.select(this).etc...
    //              ^--- 'this' is the DOM element
    

    Or:

    .on("whatever", function(d,i,n){
    //                         ^-^--- second and third arguments
        d3.select(n[i]).etc...
    //              ^--- here, 'n[i]' is also the DOM element
    

    Therefore, in your case, just use:

    .on('drag', (d,i,n) => {
        const m = d3.select(n[i]).node().getCTM();
    //the same of 'this'-----^
    ...
    }
    

    Since d3.select(n[i]) is a selection, you'll have to use node() to get the actual DOM element.

    Here is your updated plunker: https://plnkr.co/edit/tjQ6lV411vAUcEKPh0ru?p=preview

    0 讨论(0)
  • 2020-11-28 14:57

    Try using d3.event.sourceEvent.target:

    .on('drag', () => {
      const target = d3.event.sourceEvent.target;
      const m = target.getCTM();
      const x = d3.event.x - this.clickOrigin.x;
      const y = d3.event.y - this.clickOrigin.y;
      this.setClickOrigin(d3.event);
      d3.select(target)
    

    Forked Plunker Example

    0 讨论(0)
提交回复
热议问题