简体   繁体   English

无法在指令angular4中访问此对象

[英]unable to access this object in directive angular4

I am creating HTMLImageElement in the angular directive. 我在angular指令中创建HTMLImageElement。

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 . ngAfterViewInit内部, this对象可用,但在onload注册的函数内部不可用,因此我无法访问rendererel Inside onload function, this object refers to the element itself. onload函数中, this对象引用元素本身。

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? 解决办法是什么?

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 这个答案提供了一个深入的解释,在Javascript箭头和正常功能之间的差异,包括他们如何处理this

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM