循环数组角度2

时间:2017-02-27 18:14:53

标签: angular typescript

我有一个数组,我想一次只在数组中显示一个对象。一旦我有一个对象显示我然后想通过一个按钮循环通过该数组。我能够显示数组但我无法弄清楚如何一次只显示一个对象。这是我到目前为止的plunker

在这种情况下,我不确定我是否正确使用*ngFor。谢谢你的帮助!

2 个答案:

答案 0 :(得分:3)

@Component({
  selector: 'my-app',
  template: `
    <div>
      <div>{{index}}</div>
      <h2>{{item[index].title}}</h2>
      <button (click)="Next()">next</button>
    </div>
  `,
})
export class App {
  public item = ITEM;
  constructor() {}
  index = 0;

  Next(id){
    this.index ++;
    if(this.index >= this.item.length) {
      this.index = 0;
    }
  }
}

Plunker example

答案 1 :(得分:0)

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 *ngFor="let myItems of items">{{myItems.title}}</h2>
      {{index}}
      <button (click)="next()">next</button>
    </div>
  `,
})
export class App {
  public item = ITEM;
  public index = 0;

  public get items() {
    return this.item.filter((item, index) => index <= this.index);
  }
  constructor() {}

  public next(){
   this.index = Math.min(++this.index, this.item.length - 1);
  }
}