Javascript 如何对 *ngFor 应用数量限制?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36388270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I apply a quantity limit to *ngFor?
提问by Hossam Mourad
Since the Limit filter is gone from Angular 2+, how can I apply a limit for a simple *ngFor statement?
由于限制过滤器从 Angular 2+ 中消失了,我如何为简单的 *ngFor 语句应用限制?
<div *ngFor="#tweet of singleCategory">
{{ tweet }}
</div>
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.
我不希望 *ngFor 语句遍历 singleCategory 的所有元素,我想将它限制为只有 2 个结果。我相信它可以用自定义管道来完成,但我不知道如何实现它。
Thank you.
谢谢你。
回答by sqwk
You can either apply an ngIf on the element using the index:
您可以使用索引在元素上应用 ngIf :
<div *ngFor=" let tweet of singleCategory; let i=index">
<div *ngIf="i<2">
{{tweet}}
</div>
</div>
If you don't want the wrapping div, check out template syntax:
如果您不想要包装 div,请查看模板语法:
<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)
还可以选择创建管道。(请参阅链接的副本)