How to Get Current Index in ngFor
When we store data in an array, a list of employees, we can use the *ngFor
function to convert this data into a tabular format on a web page.
When we index in *ngFor
, it helps us number the list of items in an array, making it easier to track the items on the list, especially when dealing with a long range of listed items.
For example, we are dealing with a list of courses, so in the app.component.ts
, we will create the list in an array and name it courses
.
We should be mindful of the name which we give our array because that is from which we will use the *ngFor
to get the index, using the i-variable
.
In the app.component.ts
, we will input the following:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
courses = [
{ id:1, name:'course1' },
{ id:2, name:'course2' },
{ id:3, name:'course3' }
];
}
When you look at the array, you will see that it is named courses
, as we initially explained.
Next up is to go into the app.component.html
to pass in the *ngFor
function, which will be responsible for letting the array become indexed.
Here we will pass few instructions:
<ul>
<li *ngFor="let course of courses; index as i">
{{ i }} - {{ course.name }}
</li>
</ul>
Fisayo is a tech expert and enthusiast who loves to solve problems, seek new challenges and aim to spread the knowledge of what she has learned across the globe.
LinkedIn