简体   繁体   English

如何在 Angular HTML 中限制 ngFor?

[英]How can i limit ngFor in Angular HTML?

i need to ngFor with limit 4 items, but if data < 4, i need to force to loop until 4我需要 ngFor 限制 4 个项目,但如果数据 < 4,我需要强制循环直到 4

Example at this示例在此

<img *ngFor="let item of [1,2,3,4]"
    src="assets/images/no-image.jpg"
    style="border-radius: 50%; height:90%;" />

Try this way:试试这个方法:

<div *ngFor="let item of list; let i=index">
   <img *ngIf="i<4">{{item.text}}</img>
</div>

Try this way试试这个方法

<ng-container *ngFor="let item of [1,2,3,4] ; let i = index">
   <img *ngIf="i < 4"
    src="assets/images/no-image.jpg"
    style="border-radius: 50%; height:90%;" />
</ng-container>

Since you define your array somewhere in your code, the easiest way would be to slice it there.由于您在代码中的某处定义了数组,因此最简单的方法是将其切片。 Otherwise you can use the slice pipe so that you can do it right in your code.否则,您可以使用切片管道,以便您可以在代码中正确执行此操作。 See https://angular.io/api/common/SlicePipehttps://angular.io/api/common/SlicePipe

So for you you would just add | slice:0:4所以对你来说,你只需添加| slice:0:4 | slice:0:4 to the end of your ngFor | slice:0:4到 ngFor 的结尾


Edit: Sorry, I guess I should have read more carefully.编辑:对不起,我想我应该更仔细地阅读。 I wrote a Plunker Demo for this.我为此编写了一个Plunker Demo。 You can either use the pipe or the component logic solution.您可以使用管道或组件逻辑解决方案。

Plunker Demo Plunker 演示

Try this way试试这个方法

[src]="imageSrc ? imageSrc  : defaultImage"

Here imageSrc is the src of the image you wants to put and defaultImage is the src of the image if not available.这里imageSrcsrc你想要把图像和defaultImagesrc的形象,如果没有可用的。 Use this way用这种方式

<img *ngIf="i < 4">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM