I am using Photoswipe 5.4.2 with Lightbox to display full screen a bunch of images when a user clicks on an image. The problem is the first time it fails but works the second time. Here is the code I am using
In my template, I call the openLightBox() function when a user clicks on the image or div.
<div class="border-light ion-padding" (click)=openLightbox() *ngIf="images.length">
<div class="ion-padding-vertical">
<swiper-container autoplay="true" [delay]="4000" [loop]="true"[pagination]="true" [zoom]="true">
<swiper-slide *ngFor="let image of images;trackBy:trackByFn">
<img class="slide-img" src="{{image._url}}">
</swiper-slide>
</swiper-container>
</div>
</div>
Here the images variable is populated once the page is loaded and I can this because the images is displayed in the item view. For each image i get url, width and height which are required for the lightbox
prepareImageData() {
console.log(this.images.length);
for (let i = 0; i < this.images.length; i++) {
const img = new Image();
img.src = this.images[i]._url;
// Use onload event to wait for the image to load
img.onload = () => {
var height = img.height;
var width = img.width;
if (height && width) {
let data = {
src: img.src,
width: width,
height: height,
};
this.full_screen_images.push(data);
console.log(data);
}
};
}
}
Finally, I configure the lightbox and pass the full_screen_images.
async openLightbox(index: number = 0) {
await this.prepareImageData();
console.log(this.full_screen_images);
const options = {
index: index,
closeSVG:
'<svg aria-hidden="true" class="pswp__icn" viewBox="0 0 512 512" width="100" height="125"><path d="M400 145.49L366.51 112 256 222.51 145.49 112 112 145.49 222.51 256 112 366.51 145.49 400 256 289.49 366.51 400 400 366.51 289.49 256 400 145.49z"/></svg>',
zoom: false,
arrowPrev: false,
arrowNext: false,
bgOpacity: 1,
dataSource: this.full_screen_images,
};
this.lightbox = new PhotoSwipe(options);
// on() events go here (see below)
this.lightbox.init();
}