Bean0341
Bean0341

Reputation: 1697

Cycle through array angular 2

I have an array, and I want to display only one object in the array at a time. once I have one object showing I then want to cycle through that array via a button. I am able to get the array to display but I cant figure out how to just display one object at a time. Here is plunker of what I have so far.

I am not exactly sure if I am using *ngFor correctly in this case. Thanks for any help!

Upvotes: 0

Views: 964

Answers (2)

cyr_x
cyr_x

Reputation: 14257

@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);
  }
}

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658027

@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

Upvotes: 3

Related Questions