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!

2 Answers 2

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.

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

1 Comment

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!
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

1 Comment

Thank you for your help! I will keep this in mind for the future!

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.