0

I'm trying to create simple image modal using angular material. next() supposed to be view next image from the array and prev() view previous image.

Problem next and prev function not working as expected. If click next() index only increase +1 then stopped. If I click prev() index become -1

app.ts

  const imageArray = [
      {
        imageData: [
          'https://via.placeholder.com/50',
          'https://via.placeholder.com/60'
        ],
      },
      {
        imageData: [
          'https://via.placeholder.com/100'
        ],
      },
      {
        imageData: [
          'https://via.placeholder.com/150'
        ],
     }
  ];

  next() {
    this.currentImage = this.imageCollection[this.imageIndex + 1];
  }

  prev() {
    this.currentImage = this.imageCollection[this.imageIndex - 1];
  }

  processImage() {
    const rawData = this.imageArray;
    this.imageCollection = rawData.flatMap((el: any) => el.imageData);
    this.imageIndex = this.imageCollection.findIndex((x) => x === this.data.selectedImage);
    this.currentImage = this.imageCollection[this.imageIndex];
  }

app.html

<img [src]="currentImage"
     alt="customer document" />

<div (click)="next()">next</div>
<div (click)="prev()">previous</div>
Johnny
  • 261
  • 7
  • 22

2 Answers2

1

The problem is that you're not actually incrementing/decrementing this.imageIndex but merely using its value which initially as per your question was 0.

Change it like so :-

  next() {
    this.currentImage = this.imageCollection[++this.imageIndex];
  }

  prev() {
    this.currentImage = this.imageCollection[--this.imageIndex];
  }

Do add the checks when this.imageIndex goes out of bounds.

Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
1

You are not setting the this.imageIndex after you click. Try this:

  next() {
    // if is last image, then go to first image
    if(this.imageIndex === this.imageCollection.length - 1) this.imageIndex = 0;
    else this.imageIndex++;

    this.currentImage = this.imageCollection[this.imageIndex];
  }

  prev() {
    // if is first image, then go to last image
    if(this.imageIndex === 0) this.imageIndex = this.imageCollection.length - 1;
    else this.imageIndex--;

    this.currentImage = this.imageCollection[this.imageIndex];
  }
oemera
  • 3,223
  • 1
  • 19
  • 33