[英]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
<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/SlicePipe见https://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.您可以使用管道或组件逻辑解决方案。
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.这里imageSrc
是src
你想要把图像和defaultImage
是src
的形象,如果没有可用的。 Use this way用这种方式
<img *ngIf="i < 4">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.