Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through array upto only some objects using ngFor in angular 2

I'm looping through an array which has 6 objects and using ngFor where I want to loop only up to 4 elements .. How Can I do that??

<div class="item active" *ngFor="#data of lengthArray">
 content 
</div>

In LengthArray I have 6 but how to loop up to 4 records only??

and also I want to loop from 4th record to 6th record in another div.. How can I start from 4th record??

like image 745
sudhir Avatar asked Jun 30 '16 12:06

sudhir


People also ask

Does ngFor work on objects?

The ngFor directive accepts any object that implements the Iterable interface. You can read more about iterators here. So, for example, we can create our own iterable and just give it to the ngFor directive. And it just works.

Can we use two ngFor in angular?

You can't use multiple *ngFor s in the same element as those are structural directives and angular handles them in a specific way (basically for each structural directive it creates an ng-template element which then holds the directive itself, you can read more about it here: https://angular.io/guide/structural- ...

Why * is used in ngFor?

In *ngFor the * is a shorthand for using the new angular template syntax with a template tag, this is also called structural Directive.It is helpful to know that * is just a shorthand to explicitly defining the data bindings on a template tag.

Which is the correct syntax of ngFor in angular?

The syntax is *ngFor="let <value> of <collection>" . <value> is a variable name of your choosing, <collection> is a property on your component which holds a collection, usually an array but anything that can be iterated over in a for-of loop.


2 Answers

You can use the slice pipe with a start and end parameter. The start parameter is required and the end parameter is optional.

<div class="item active" *ngFor="#data of lengthArray | slice:start[:end]">
  content 
</div>
like image 115
muetzerich Avatar answered Oct 27 '22 16:10

muetzerich


You can capture the index and then make it less then 4

<div class="item active" *ngFor="#data of lengthArray;i=index">
    <div *ngIf="i<=4">
        content
    </div>
</div>

I haven't really tested the code but you can find a lot of examples here on stackoverflow, do more researching...

Angular 2: how to apply limit to *ngFor?

More about filters... How to apply filters to *ngFor

like image 34
Marko Avatar answered Oct 27 '22 17:10

Marko