带有next / prev链接的图像滑块

时间:2017-09-15 09:36:02

标签: angular

我想制作一个图像滑块(角度为4),每次显示5张图像,每侧有上一个/下一个按钮。只有当用户按下按钮(不是轮播,更像是分页)时,才会获取要显示的新图像。

HTML(简化):

<div class="row">
    <div class="col-md-1">
      <button (click)="prev()"></button>
    </div>
    <div class="col-md-10">
      <div *ngFor="let image of images">
        <div class="col-md-2">
          <img>{{image}}</img>
        </div>
      </div>
    </div>
    <div class="col-md-1">
      <button (click)="next()"></button>
    </div>
  </div>

Thanx:)

2 个答案:

答案 0 :(得分:0)

如果你有所有图片的网址,那么把它们放到一个数组中,当调用click方法时,只记录索引,当有人按下时增加索引号,如果按prev,则将索引号减1。在视图中使用 <img [src]="imageToShow" />

喜欢:

let imageArray = ['x.jpg','y,jpg','z.jpg','m.jpg'];
let index= 0;
let imageToShow = '';
prev(){
    index = index<=0 ? 4 : index--; 
    imageToShow =  imageArray[index] ;

} 
next(){
    index = index>=4 ? 0 : index++;
    imageToShow =  imageArray[index] ;
}

`

答案 1 :(得分:0)

如果有人想知道我是如何解决的:

      <div class="row">
      <div class="col-md-1">
        <i class="fa fa-chevron-left fa-lg" (click)="prev()" style="cursor: pointer;"></i>
      </div>
      <div class="col-md-10 row">
        <div *ngFor="let image of imageArrayToDisplay">
          <div class="col-md-2">
            <img [src]="image" />
          </div>
        </div>
      </div>
    </div>
    <div class="col-md-1">
      <i class="fa fa-chevron-right fa-lg" (click)="next()" style="cursor: pointer;"></i>
    </div>
  </div>

组件:

displayIndex = 0;
displaySize = 5; //No of images to show at the same time
imageArray = ['1.jpg','2,jpg','3.jpg','5.jpg','6.jpg','7,jpg','8.jpg','9.jpg'];
imageArrayToDisplay: string[] = []; 

ngOnInit() {
 //initially display 5 first images
 this.imageArrayToDisplay = this.imageArray.slice(0, this.displaySize);
}

 prev() {
    this.displayIndex = this.displayIndex - 1;

    // Start of list, start at end of list and move backwords
    if (this.displayIndex < 0) {
        this.displayIndex = (this.imageArray.length / this.displaySize) - 1;
        const start = this.displayIndex * this.displaySize;
        this.imageArrayToDisplay = this.imageArray.slice(start, (start + this.displaySize));
    } else {
        const start = this.displayIndex * this.displaySize;
        this.imageArrayToDisplay = this.imageArray.slice(start, (start + this.displaySize));
    }
}

next() {
    this.displayIndex = this.displayIndex + 1;

    // End of list, start from beginning
    if (this.imageArray.length <= (this.displayIndex * this.displaySize)) {
        this.imageArrayToDisplay = this.imageArray.slice(0, this.displaySize);
        this.displayIndex = 0;
    } else {
        const start = this.displayIndex * this.displaySize;
        this.imageArrayToDisplay = this.imageArray.slice(start, (start + this.displaySize));
    }
}