[英]Angular directive to check if all images have been fully loaded
所以我在我的 Angular 应用程序中有一个画廊幻灯片部分,我使用 Swiperjs 来处理所有的滑动内容。 无论如何,为了让 Swiperjs 正常工作,我需要在初始化 Swiperjs 之前加载所有图像。 因此我的问题是,如何创建一个指令来查找组件及其子组件中的所有图像并检查所有图像是否已加载?
到目前为止,我有一个指令可以检查父组件GalleryComponent
中的所有图像标签并记录“Img Loaded”。 以下是我的指令:
import { Directive,ElementRef, HostListener } from '@angular/core'; @Directive({ selector: 'img' }) export class ImagesLoadedDirective { constructor(public elementRef:ElementRef) { } @HostListener("load") imageLoaded() { console.log("img loaded"); /* Can I do something like "return true" for every image that loaded? And how would I register that in my Gallery Component*/ } }
我已将指令包含在我的GalleryComponent
中,如下所示:
@ViewChildren(ImagesLoadedDirective) images:QueryList<ImagesLoadedDirective>;
我想下一步是以某种方式保存已加载的每个图像,一旦完成
我可以这样说this.allImagesLoaded = true
,然后初始化 Swiperjs? 感谢任何输入。
您可以使用EventEmitter
通知订阅者图像已加载。 然后只需在根组件中通过forkJoin
组合所有这些Observables
。 加载所有图像后,您将在forkJoin
订阅中收到通知。
指令.ts
@Directive({
selector: 'img',
})
export class ImgLoadedDirective {
@Output() loaded = new EventEmitter();
@HostListener('load')
@HostListener('error')
imageLoaded() {
this.loaded.emit();
this.loaded.complete();
}
}
父.ts
@ViewChildren(ImgLoadedDirective) images: QueryList<ImgLoadedDirective>;
ngAfterViewInit() {
forkJoin(this.images.map(imgDir => imgDir.loaded)).subscribe(() => {
console.log('all images have been loaded');
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.