简体   繁体   中英

Angular directive to check if all images have been fully loaded

So I have a gallery slide section in my Angular app and I am using Swiperjs for all the sliding stuff. Anyhow so for Swiperjs to work properly I need all the images to be loaded before Swiperjs is initialised. Hence my question, how can I create a directive that will look for all the images in the component and its child component and check if all the images have been loaded?

So far I have a directive that checks for all the Image tags in the parent component GalleryComponent and logs "Img Loaded". Below is my directive:

 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*/ } }

I have included the directive in my GalleryComponent as such:

 @ViewChildren(ImagesLoadedDirective) images:QueryList<ImagesLoadedDirective>;

I suppose the next step is to somehow save each image that has been loaded, and once that is done
I can say something like this.allImagesLoaded = true , then initialize Swiperjs? Appreciated any input.

You can use EventEmitter to notify subscribers that image has been loaded. Then just combine all those Observables through forkJoin in your root component. Once all images are loaded you will be notified in forkJoin subscription.

directive.ts

@Directive({
  selector: 'img',
})
export class ImgLoadedDirective {
  @Output() loaded = new EventEmitter();

  @HostListener('load')
  @HostListener('error')
  imageLoaded() {
    this.loaded.emit();
    this.loaded.complete();
  }
} 

parent.ts

@ViewChildren(ImgLoadedDirective) images: QueryList<ImgLoadedDirective>;

ngAfterViewInit() {
  forkJoin(this.images.map(imgDir => imgDir.loaded)).subscribe(() => {
    console.log('all images have been loaded');
  });
}

Ng-run Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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