3

On my website if I have more than one element in my array. My template looks like this.

Browser Image

I want to have a button to go to the next element of this array and only display one set of data and use the button to control which element of the array the user sees.

My current code looks like this:

<div class='panel-body' *ngIf ='case'>

        <h3> Details </h3>
        <div id="left-side" *ngFor="let tag of case?.incidents ">
            <p>Date: <span class="name">{{tag.date}}</span> </p>
            <p>DCU: <span class="name">{{tag.dcu}}</span></p>
            <p>Location:<span class="name"> {{tag.location}}</span> </p>
        </div>

I was thinking of using some sort of index or an ng-container or some work around using ngIf or ngFor. I am unsure of how to implement this.

All help would be greatly appreciated!

Edward Muldrew
  • 77
  • 1
  • 13

2 Answers2

3

To achieve this you can use angular's default SlicePipe like this example,

@Component({
  selector: 'slice-list-pipe',
  template: `<ul>
    <li *ngFor="let i of collection | slice:1:3">{{i}}</li>
  </ul>`
})
export class SlicePipeListComponent {
  collection: string[] = ['a', 'b', 'c', 'd'];
}

You can find more details here

Gowtham
  • 3,198
  • 2
  • 19
  • 30
3

You're not going to need an ngFor or ngIf in this situation. What you'll want is a variable to keep track of the user's index, and then a function that changes that index.

<h3> Details </h3>
<div id="left-side" >
    <p>Date: <span class="name">{{case?.incidents[userIndex].date}}</span> </p>
    <p>DCU: <span class="name">{{case?.incidents[userIndex].dcu}}</span></p>
    <p>Location:<span class="name"> {{case?.incidents[userIndex].location}}</span> </p>
</div>
<button (click)="changeIndex(-1);">Previous</button>
<button (click)="changeIndex(1);">Next</button>

and in your component.ts you'll have:

userIndex = 0;

changeIndex(number) {
  if (this.userIndex > 0 && number < 0 ||  //index must be greater than 0 at all times
  this.userIndex < this.case?.incidents.length && number > 0 ) {  //index must be less than length of array
    this.userIndex += number;
  }

This will be a standard for in-view paging systems for other projects as well.

Z. Bagley
  • 8,942
  • 1
  • 40
  • 52
  • 1
    Thank you so much for your answer! This is perfect. I felt I was along the right lines but I wasn't 100% sure with how to reference certain things as well with referencing using the right structural directive! – Edward Muldrew Jun 29 '17 at 15:01