[英]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.