0

我正在尝试使用角度材料创建简单的图像模式。next()应该从数组中查看下一个图像并prev()查看上一个图像。

问题 next 和 prev 功能无法按预期工作。如果单击 next() 索引只增加 +1 然后停止。如果我单击 prev() 索引变为-1

应用程序.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];
  }

应用程序.html

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

<div (click)="next()">next</div>
<div (click)="prev()">previous</div>
4

2 回答 2

1

问题是您实际上并没有增加/减少this.imageIndex,而只是使用最初根据您的问题为 0 的值。

像这样改变它: -

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

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

this.imageIndex超出范围时添加检查。

于 2021-03-09T16:44:24.867 回答
1

this.imageIndex单击后您没有设置。尝试这个:

  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];
  }
于 2021-03-09T16:49:33.370 回答