将同一指令应用于单个组件中的许多 div,将该指令的事件侦听器仅附加到最后一个



我在单个组件上有 50 个div。我正在制定一个名为"lazyload"的指令。然后我将此指令应用于所有这些div。在"lazyload"指令的onInit中,我已经注册了滚动事件。滚动的事件侦听器函数应该检查这个div(在我的例子中,应用此指令的所有这 50 个div(是否在视口内,然后对该特定div 执行一些操作。但似乎这个滚动事件只为我视图的最后一个div 注册。

我的组件模板:

<div class="product-container" *ngFor="#product of allProducts">
            <div class="product-image" 
            [lazyLoadImage]="product.image" >
            </div>
            <div class="product-desc">
                <p>{{product.name}}</p>
                <p> <span>{{product.price | currency:'INR':true}}</span> <span>{{product.monthDiff + " months"}}</span> </p>
            </div>
        </div>

指令"lazyLoadImage"是:

@Directive({
    selector: '[lazyLoadImage]'
})
export class LazyLoadImgDirective {
    private _el: HTMLElement;
    private _canLoadImage: boolean = false;
    private _imgUrl: string;
    @Input()
    set lazyLoadImage(v){
        this._imgUrl = v;
        if(v){
            this.attachEvent()
        }
    }
    constructor(el: ElementRef, private _utils:UtilServices) { this._el = el.nativeElement;}
    private _loadingDone: boolean = false;
    loadImage(){
      //some operations
    }
    attachEvent() {
        console.log("inside image load dir");
        var self = this;
        setTimeout(() => self.loadImage(), 1);
        window.onscroll = (event) => {
            console.log("scrolling intercepted for: "+self._imgUrl);//log is shown only for the last element where this directive is applied
            if (!self._loadingDone){
                setTimeout(() => self.loadImage(), 1);
            }
        }
    }
}

滚动的事件侦听器仅在迭代中的最后一个产品上工作。

正如@yurzui所说,您正在重写事件处理程序。

普伦克示例

我还修复了代码中的其他一些问题(如果您使用 => 和其他一些问题,则无需self = this(。

ElementRef null,因为没有, private _utils:UtilServices提供程序。删除此参数将设置ElementRef

最新更新