Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What loop-types exist in Angular 2?

Tags:

loops

angular

What are the types of loops that exist in Angular 2?

I could only find for and foreach, but I'm having trouble to find any other ones. Is there a list somewhere?

Are there examples somewhere? That would help in understanding very strongly.

[EDIT]: What I am essentially looking for is a list of all the different loop types in Angular 2.

[EDIT 2]: What I really mean are the loops specific to Angular 2 within the template-section (Sorry, I didn't know there were so many possibilities). To give an example with *ngFor:

<ul class="contacts">
  <li *ngFor="#contact of contacts"
      (click)="onSelectContact(contact)"
      [class.selectedContact]="contact === selectedContact">
    <span class="badge">{{contact.id}}</span> {{contact.name}}
  </li>
</ul>
like image 292
Socrates Avatar asked Jan 14 '16 02:01

Socrates


People also ask

What is use of for loop in angular?

The for–in loop is for looping over object properties. The for–of loop is for looping over the values in an array. for–of is not just for arrays. It also works on most array-like objects including the new Set and Map types which we will cover in the next lecture.

What is* ngFor in angular?

*ngFor is a predefined directive in Angular. It accepts an array to iterate data over atemplate to replicate the template with different data. It's the same as the forEach() method in JavaScript, which also iterates over an array.

How ngFor works in angular?

NgFor is a structural directive, meaning that it changes the structure of the DOM . It's point is to repeat a given HTML template once for each value in an array, each time passing it the array value as context for string interpolation or binding.


2 Answers

The only template loop directive in Angular 2 is ngFor, and it only works with iterables, typically arrays. (In Angular 1, ng-repeat would also work with objects, but Angular 2 does not.)

You can use a pipe to format, filter, sort, etc. the list before displaying it.

like image 100
Mark Rajcok Avatar answered Oct 05 '22 03:10

Mark Rajcok


You can use the ngFor directive in Angular 2 for looping/iterating.

Like this

<li *ngFor="#item of items; #i = index">...</li>

Documentation for this directive can be found here https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html

And an example of this being done within the Developer Guides on Angular 2's website https://angular.io/docs/ts/latest/guide/displaying-data.html#!#showing-an-array-property-with-ngfor

like image 20
Steve Livingston Avatar answered Oct 05 '22 02:10

Steve Livingston