如何在angular2中显示ngFor中的1个元素?

时间:2017-02-25 16:35:47

标签: arrays angular tags angular-ng-if ngfor

我有一个简单的ngFor循环数组。但是,我添加了一个条件,即当索引为< 5时,请继续添加标记。之后,我想添加一个额外的标签,只需使用一个下拉列表来查看其余的标签。但它不起作用。

<li *ngFor="let tag of module.Tags; let i = index">
  <a *ngIf="i<5" href="#" class="span-tag tag">{{ tag }}</a>
  <div *ngIf="module.Tags.length > 5 && i == 6">DropDown Button</div>
</li>

这里的功能是我不想向用户显示无限数量的标签,我想将其限制为仅5个标签,并且在5个标签后面有一个按钮,用于显示下拉列表剩下的标签。

这是否可以在angular2中进行?

如果是的话,请赐教。

1 个答案:

答案 0 :(得分:5)

<li *ngFor="let tag of module.Tags | slice:0:5; let last=last">
  <a href="#" class="span-tag tag">{{ tag }}</a>
  <div *ngIf="last">DropDown Button</div>
</li>

https://angular.io/docs/ts/latest/api/common/index/SlicePipe-pipe.html

要添加所有内容,但在第5项之后添加了<div>DropDown Button</div>,您可以使用:

show = 5;

<li *ngFor="let tag of module.Tags|slice:0:show let i=index">
  <a href="#" class="span-tag tag">{{ tag }}</a>
  <div *ngIf="i==4 && show == 5" (click)="show = module.Tags.length">DropDown Button</div>
</li>