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

3
在我的网站上,如果我的数组中有多个元素。我的模板看起来像这样。 Browser Image 我想要一个按钮来进入这个数组的下一个元素,并且只显示一组数据,使用按钮来控制用户看到数组的哪个元素。
我的当前代码如下:
<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-container,或者使用ngIf或ngFor来解决问题。但我不确定如何实现。

非常感谢您的帮助!

2个回答

3
为了实现这一点,您可以使用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'];
}

您可以在这里找到更多详细信息。


谢谢你的帮忙!我会记住这个,以备将来之需! - Edward Muldrew

3

在这种情况下,您不需要使用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>

在您的组件.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;
  }

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

1
非常感谢您的回答!这太完美了。我感觉自己走在正确的路上,但是我不确定如何引用某些内容以及使用正确的结构指令进行引用! - Edward Muldrew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接