Search code examples
htmlarraysangularngforangular-ng-if

How to show 1 element in an array using ngFor Angular2


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!


Solution

  • 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.