0
 export class FloorPlanComponent implements AfterViewInit, OnInit {
      constructor();
      constructor(public _baseComponentService?: BaseComponentService,
                  public _internalZoneService?: InternalZoneService,
                  public routeParams?: ActivatedRoute,
                  public internalAssetService?: InternalAssetService,
                  public slimLoadingBarService?: SlimLoadingBarService,
                  private errorLoggerService?: ErrorLoggerService
                 ) {
                     if (this._baseComponentService != null) {
                           this._baseComponentService.SetPageTitle("Zones - Internal");
                   }
      this.imgDelZone = parentElement.append("image")
        .attr("id", "delZone" + newId)
        .attr("idCounter", newId)
        .attr("r", "NaN")
        .attr("stroke-width", 0)
        .attr("opacity", 0.8)
        .attr("x", function (d) { return d.x + (shapeWidth - 22); })
        .attr("y", function (d) { return d.y + 1; })
        .attr("style", "opacity: 1; stroke-width: 1;")
        .attr("xlink:href", "../app/assets/images/Remove_Delete-22.png")
        .attr("preserveAspectRatio", "none")
        .attr("transform", " ")
        .attr("height", 18)
        .attr("width", 18)
        .attr("cursor", "pointer").on("click", function () {
            var comp = new FloorPlanComponent();
            comp.promptDeleteZone(this);
        });
}

Inside "click" function, I want to use this to refer my class. But it's referring this as a window object. To resolve this issue, I created a object of class with the help of parameterless constructor. But according to this, I'm unable to get any service. Please help.

Shamas S
  • 7,507
  • 10
  • 46
  • 58

2 Answers2

0

You might use arrow function:

  attr("cursor", "pointer").on("click", () => {
    ...
  });

Arrow functions capture the this where the function is created so this will point to FloorPlanComponent instance.

  • Thanks Alexander for quick reply. I have one more scenario where I'm stuck. See below code. drag: any = d3.drag().on("drag", this.dragmove); in dragmove(d) function, I want this as a floorplancomponent as well as get this object of selected drag item. How is it possible. – ranjan srivastav Sep 18 '17 at 05:00
  • You could just save pointer to `this` in local variable and use closure to access it: `let self = this; drag: any = d3.drag().on("drag", function() { let dragItem = this; self.dragmove(dragItem); });` – Alexander Matyushentsev Sep 18 '17 at 05:10
  • it's not working. I used self:any=this; (in the class root level). Inside the function, self still refer to window object. – ranjan srivastav Sep 18 '17 at 05:48
0

How about

.attr("cursor", "pointer").on("click", this.onClicked.bind(this));

.............
onClicked() {
    var comp = new FloorPlanComponent();
    comp.promptDeleteZone(this);
}
Huy Nguyen
  • 85
  • 1
  • 3