Accessing the index value of the iteration

We'll often be interested in having access to the index value of the iteration—maybe to grab every nth object, or to group things in numbers of x, or maybe we want to implement some kind of custom pagination. Whatever the need to read the current index value of the iteration, we can use the index keyword to set the index to a variable within our expression.

Here's some example code demonstrating this:

<ul> 
<li *ngFor="let car of cars; let i = index">
Car #{{ i + 1 }}: {{ car.model }}
</li>
</ul>

In the previous code sample, let's just assume that the cars collection was populated elsewhere—such as in the component class.

Also, Angular takes care of updating the index value with each iteration for us—and all we have to do is to reference it.

Note that we use {{ i + 1 }} to output the car number. This is because, as with most arrays or iterables (in most languages, but certainly in JavaScript and TypeScript), the index is zero-based. Also, note that the expression within the double curly braces, i + 1, is not just a variable. In Angular, whatever is inserted within the double curly braces is evaluated. We could even insert function calls there if we wanted to.

The official online documentation for structural directives is available at https://angular.io/guide/structural-directives.

..................Content has been hidden....................

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