如何使用 ngFor Angular2 在数组中显示 1 个元素

How to show 1 element in an array using ngFor Angular2

在我的网站上,如果我的数组中有多个元素。我的模板看起来像这样。

我想要一个按钮去这个数组的下一个元素并且只显示一组数据并使用按钮来控制用户看到数组的哪个元素。

我当前的代码如下所示:

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

我正在考虑使用某种索引或 ng 容器,或者使用 ngIf 或 ngFor 进行一些变通。我不确定如何实现这一点。

所有帮助将不胜感激!

要实现这一点,您可以使用 angular 的默认 SlicePipe 就像这个例子,

@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'];
}

您可以找到更多详细信息here

在这种情况下您不需要 ngFor 或 ngIf。您需要的是一个用于跟踪用户索引的变量,然后是一个更改该索引的函数。

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

在您的 component.ts 中,您将拥有:

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

这也将成为其他项目的视图内分页系统的标准。