增量在prev中不起作用,下一个按钮Angular 4

时间:2017-07-04 07:44:19

标签: javascript angular

我必须创建一个prev和next组件,使用Angular的路由器转到下一页。问题不在于角度,而在于递增和递减逻辑。

当我第一次点击下一次是好的,但第二次我必须点击两次才能看到下一页。使用prev按钮也会发生同样的情况。如果我想点击返回,在我第一次点击后,我必须点击两次才能转到上一页。

我看了看,我看了,看不出那个虫子在哪里。

HTML文件

<button class="btn btn-primary" (click)="prevPage()">Prev</button>  
<button class="btn btn-primary" (click)="nextPage()">Next</button>

TS文件

pages = [
 {name: '../page1', index: 0}, 
 {name: '../page2', index: 1}, 
 {name: '../page3', index: 2}
];
current = this.pages[0];

getIndex(currentIndex: number, shift: number){
 const lenght = this.pages.length;
 const incre = (((currentIndex + shift) + lenght) % lenght);
 console.log(incre);
 return incre;
}

prevPage() {
 const i = this.getIndex(this.current.index, -1);
 this.current = this.pages[i];
 this.router.navigate([this.current.name], { relativeTo: this.route });
 console.log(this.current.name);  
}

nextPage() {
 const i = this.getIndex(this.current.index, 1);
 this.current = this.pages[i];
 this.router.navigate([this.current.name], { relativeTo: this.route });
 console.log(this.current.name);   
}

1 个答案:

答案 0 :(得分:0)

在HTML文件中。

<button class="btn btn-primary" (click)="prevPage()">Prev</button>  
<button class="btn btn-primary" (click)="nextPage()">Next</button>

将(click)侦听器更改为nextPage()。

加上,

中的(+长度)没有意义
  

const incre =(((currentIndex + shift)+ lenght)%lenght);

没有它,它会正常工作!

  

const increment =((currentIndex + shift)%lenght);