Advanced looping

Besides from just looping all the items in a list, it is possible to keep track of other usable properties as well. Every property can be used the same way by us adding another statement after the declaration of the items:

<div *ngFor="let items of items; let property = property">{{ item }}</div>

First/last, this is a Boolean that keeps track of whether we are on the first or last item in our loop, should we want to render that item differently. It can be accessed in the following way:

<div *ngFor="let item of items; let first = first">
<span [ngClass]="{ 'first-css-class': first, 'item-css-class' : !first }">
{{ item }}
</span>
</div>

Index, is a number to tell us what index we are on; it starts at 0.

Even/odd is a Boolean to indicate whether we are even on an even or odd index.

TrackBy, to explain what trackBy does, let's first talk about the problem it attempts to solve. The problem is that the data the  *ngFor is pointing to may change, elements may be added or removed, and even the whole list may be replaced. The naive approach to the adding/removing of elements is to carry out create/remove on the DOM tree for all those elements. If same naive approach is used for displaying a new list instead of the old list we used to display this, it will be very expensive and slow. Angular deals with this by keeping DOM elements in memory because creation is costly. Internally, Angular uses something called object identity to keep track of every item in a list. trackBy, however, allows you to change from object identity to a specific property on your item. The default object identity is good in most cases, but if you start experiencing performance problems consider changing what property on your item *ngFor should look at like so:

@Component({
template : `
<*ngFor="let item of items; trackBy: trackFunction">{{ item }}</div>
`
})
export class SomeComponent {
trackFunction(index, item) {
return item ? item.id : undefined;
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset