How to use *ngFor in Angular

In this post, We are going to explain *ngFor and all features of *ngFor means local variables and find index etc.

*ngFor

NgFor is a structural directive, means, it changes the structure of the DOM

Its 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 syntax is *ngfor=”let <value> of <collections>”

<value> is variable name of your choosing, <collection> is property on your component which holds a collection, usually an array but anything that can be iterate over in a for loop.

Example:-

 




ngFor-local variables

Index – Used for provide the index for current element while iteration.

First –  Return true if current element is first element in the iteration otherwise false.

Last — Return true if current element is last element in the iteration otherwise false.

Even – Return true if current element is even element based on index in iteration otherwise false.

Odd — Return true if current element is odd element based on index in iteration otherwise false.

 

Index with *ngFor directive

Sometimes we also want to get the index of the item in the array we are iterating over.

We can do this by adding another variable to our ngFor expression and making it equal to index.

The index is always zero based, So starts at 0 then 1,2,3,..etc.

Example:- 

 



Even & Odd with *ngFor directive

Even and Odd both provides the boolean value, Returns true if current element value is even element based on index or odd element based on index otherwise false.

 

TrackBy with *ngFor directive

The use of track by its a performance optimization and is usually not needed by default, Its in principal only needed if running into performance issues.

Suppose we have some data coming from some API request into the collection and we need to change the data over the web page

Example:- 

 

Thanks!!

Add a Comment

Your email address will not be published. Required fields are marked *