Get index of ngFor element using index as value in attribute

Get index of ngFor element using index as value in attribute

This tutorial guides you on how to get index of ngFor element using index as value in attribute in Angular.

Get index of ngFor element using index as value in attribute

In our previous tutorial display JSON response from REST API we have seen how to use ngFor to render an JSON array in the HTML view and how to work with each element of the list using statement “let element of jsonArray”. Here we used “let” statement to define a variable called “element” that was used to hold the reference of the current array element.

Note, only having those references to each element alone is not enough. And in certain use cases you may require to number each list element using the index value of that element.

The below example code sneppet shows how to get index of element using ngFor directive. You need to define another variable called “i” and assign the value of “index” to that variable as shown in the example below.

Afterwards, you just have to use that “i” variable inside the flower brackets”{{}}” just like any-other variables as shown to display the index in HTML view.

<ul>

    <li *ngFor="let element of jsonArray; let i = index">
       {{i}}, {{element.username}}, {{element.uid}}, {{element.age}}
    </li>

</ul>

Example: Get index of ngFor element

The component template should look like below.

mycomponent.component.html

<p>This is My First Component</p>

<ul>
 
    <li *ngFor="let element of jsonArray; let i = index">
       {{i}}, {{element.username}}, {{element.uid}}, {{element.age}}
    </li>
 
</ul>

And your angular component class file should have the following code.

mycomponent.component.ts

import { Component } from '@angular/core';

@Component({
	
	selector:'app-mycomp',
	templateUrl:'./mycomponent.component.html'

})

export class MycomponentComponent {

	jsonArray = [
		{
		  uid: '10',
		  age: 22,
		  username: 'John Paul',
		},
		{
		  uid: '11',
		  age: 35,
		  username: 'Peter Jackson',
		},
		{
		  uid: '12',
		  age: 30,
		  username: 'Will Smith',
		},
		{
		  uid: '13',
		  age: 25,
		  username: 'Peter Paul',
		},
		{
		  uid: '14',
		  age: 34,
		  username: 'Johnson Peter',
		},
		{
		  uid: '15',
		  age: 30,
		  username: 'Eric Smidth',
		},
	  ]

	
}

Then, use the component selector ‘app-mycomp‘ in your parent component (app.component.html).

app.component.html

<div class="container">
	<div class="row">
		<div class="col-xs-12">			
			<h3>My First Component !</h3> 
			<hr>
			<app-mycomp></app-mycomp>		
		</div>
	</div>
</div>

Finally, when you run the above example you should see the following output in the browser.

Output:  Index of each ngFor element

Get index of ngFor element using index as value in attribute

That’s it. Hope it helped 🙂

Also See:

References:

guest
0 Comments
Inline Feedbacks
View all comments