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>
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.
*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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With