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>
0

2 Answers 2

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];
  }
Sign up to request clarification or add additional context in comments.

2 Comments

When I clicked next() second time, index goes 1 to 3. It's skipping index 2
@Johnny i suspect that's unrelated to the code solution provided here
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.

1 Comment

When I clicked next() second time, index goes 1 to 3. It's skipping index 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.