如何将数量限制应用于* ngFor? [英] How can I apply a quantity limit to *ngFor?

查看:381
本文介绍了如何将数量限制应用于* ngFor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于限制过滤器已从Angular 2+中删除,如何对简单的* ngFor语句应用限制?

Since the Limit filter is gone from Angular 2+, how can I apply a limit for a simple *ngFor statement?

<div *ngFor="#tweet of singleCategory">
  {{ tweet }}
</div>

我不希望* ngFor语句循环遍历singleCategory的所有元素,我想要将其限制为仅2个结果。我相信可以使用Custom Pipes完成,但我不知道如何实现它。

I don't want the *ngFor statement to loop through all the elements of singleCategory, I want to limit it to just 2 results. I believe that it could be done with Custom Pipes but I don't know how to implement it.

谢谢。

推荐答案

您可以使用索引在元素上应用ngIf:

You can either apply an ngIf on the element using the index:

<div *ngFor=" let tweet of singleCategory;  let i=index">
    <div *ngIf="i<2">
        {{tweet}}
    </div>
</div>

如果您不想要包装div,请查看模板语法

If you don't want the wrapping div, check out template syntax:

<ng-template ngFor let-tweet [ngForOf]="singleCategory" let-i="index">
    <div [ngIf]="i<2">
        {{tweet}}
    </div>
</ng-template>

最好先使用过滤器过滤元件中的元素,以防止在显示数据时出现不必要的循环:

Preferably you first/instead filter the elements in your component using filter to prevent unnecessary loops when displaying your data:

public get singleCategory() {
   return this.categories.filter((item, index) => index > 2 )
}

还可以选择创建管道。 (参见链接的副本)

There is also the option of creating a pipe. (See the linked duplicate)

这篇关于如何将数量限制应用于* ngFor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆