我正在我的Angular(5)应用程序中实现一个懒惰的图像加载器,我很好奇如何可以避免在我的ngAfterViewInit()中调用setTimeout().
代码的相关部分是:
# component
ngOnInit(): void {
this.workService.getCategories().then(workCategories => {
this.workCategories = workCategories;
});
}
ngAfterViewInit(): void {
setTimeout(() => {
const images = Array.from(document.querySelectorAll('.lazy-image'));
}, 100);
}
# component template
<div *ngFor="let workCategory of workCategories">
<h3>{{ workCategory.fields.name }}</h3>
<div *ngFor="let workSample of workCategory.fields.workSamples">
<img width="294" height="294" class="lazy-image" src="..." data-src="..." />
</div>
</div>
如果我删除setTimeout(),则images数组始终为空. AfterViewInit应在创建所有子组件后运行.我也尝试过AfterContentinit,它的行为与AfterContentChecked相同,后者崩溃了Chrome.
在这种情况下是否可以避免使用setTimeout?
解决方法:
This stackblitz显示了使用ngFor指令创建元素时获得通知的一种方法.在模板中,您将模板引用变量#lazyImage分配给img元素:
<div *ngFor="let workCategory of workCategories">
...
<div *ngFor="let workSample of workCategory.fields.workSamples">
<img #lazyImage width="294" height="294" class="lazy-image" src="..." data-src="..." />
</div>
</div>
在代码中,@ ViewChildren(“lazyImage”)用于声明QueryList< ElementRef>与这些图像相关联.通过在ngAfterViewInit中订阅Querylist的更改事件,您可以在元素可用时收到通知.然后可以从QueryList检索HTML元素:
import { Component, ViewChildren, AfterViewInit, QueryList } from '@angular/core';
@Component({
...
})
export class AppComponent {
@ViewChildren("lazyImage") lazyImages: QueryList<ElementRef>;
ngAfterViewInit() {
this.lazyImages.changes.subscribe(() => {
let images = this.lazyImages.toArray().map(x => x.nativeElement);
});
}
}
如果只处理最后创建的项目,可以使用QueryList.last:
this.lazyImages.changes.subscribe(() => {
this.doSomethingOnLastimage(this.lazyImages.last);
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。