1

I am creating HTMLImageElement in the angular directive.

ngAfterViewInit() {
    this.renderer.setAttribute(this.el.nativeElement, "src", this.onePxlImgPlaceHolder);

    // create HTML image element to load image in the background
    this.dynamicImg = new Image();
    // register the function that will be called on image load
    this.dynamicImg.onload = function () {
        this.renderer.setAttribute(this.el.nativeElement, "src", this.dynamicImg.src);
    };

    this.dynamicImg.src = this.originalImgSrc;
}

Inside the ngAfterViewInit, this object is available but inside the function that is registered with onload is not available, so I cannot access renderer and el. Inside onload function, this object refers to the element itself.

I have even tried

this.dynamicImg.onload = function () {
            this.renderer.setAttribute(this.el.nativeElement, "src", this.dynamicImg.src);
    }.bind(this);

not working!! What is the solution?

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189

1 Answers1

3

You can use an arrow function to keep the scope:

this.dynamicImg.onload = () => {
  this.renderer.setAttribute(this.el.nativeElement, "src", this.dynamicImg.src);
};

This answer provides an in-depth explanation of the differences between arrow and normal functions in Javascript, including how they handle this

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
bugs
  • 14,631
  • 5
  • 48
  • 52