最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to limit number of items to get displayed in ngFor? - Stack Overflow

programmeradmin3浏览0评论

I want the display only the first 3 items from a list using *ngFor

On my ponent,

formInputs: any = [
{name:'foo'},
{name: 'bar'},
{name: 'buzz},
{name: 'dhsfk'},
{name: 'sadsd'}
]

On my template,

<div class="form-group label-floating" *ngFor="let input of formInputs">
{{input.name}}
</div>

And note that, I want to apply the change only in the template itself not in the ponent.

I want the display only the first 3 items from a list using *ngFor

On my ponent,

formInputs: any = [
{name:'foo'},
{name: 'bar'},
{name: 'buzz},
{name: 'dhsfk'},
{name: 'sadsd'}
]

On my template,

<div class="form-group label-floating" *ngFor="let input of formInputs">
{{input.name}}
</div>

And note that, I want to apply the change only in the template itself not in the ponent.

Share Improve this question edited Jan 6, 2017 at 9:24 Avinash Raj asked Jan 6, 2017 at 9:21 Avinash RajAvinash Raj 175k31 gold badges245 silver badges287 bronze badges 2
  • Don't know why slice not mentioned in the ngFor doc.. – Avinash Raj Commented Jan 6, 2017 at 9:30
  • I have also provided the documentation link dude. It's an array function. So it's not given in ngFor. angular.io/docs/ts/latest/api/mon/index/SlicePipe-pipe.html – Praveen Kumar Purushothaman Commented Jan 6, 2017 at 9:31
Add a ment  | 

2 Answers 2

Reset to default 10

You can use the slice pipe for that

<div class="form-group label-floating" *ngFor="let input of formInputs | slice:0:3">
  {{input.name}}
</div>

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

Using slice:

Creates a new List or String containing a subset (slice) of the elements.

array_or_string_expression | slice:start[:end]
*ngFor="let input of formInputs | slice:0:3"

Change your code:

<div class="form-group label-floating" *ngFor="let input of formInputs | slice:0:3">
  {{input.name}}
</div>
发布评论

评论列表(0)

  1. 暂无评论