Code Guru
Code Guru

Reputation: 15598

unable to access this object in directive angular4

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?

Upvotes: 1

Views: 38

Answers (1)

bugs
bugs

Reputation: 15323

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

Upvotes: 3

Related Questions