0

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!

2
  • You don't need ngFor to display a single value. All you need is the index that you want to display: {{ myArray[theDisplayedIndex] }}. Nowincrement theDisplayedIndex with your button, and you have the solution. Commented Feb 27, 2017 at 18:17
  • Please provide all relevant code in an minimal reproducible example in the question itself, not on a third-party site. Commented Feb 27, 2017 at 18:19

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.