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:-
1 2 3 4 5 6 | <ul *ngFor="let employee of employees"> <li class="text-success">{{ employee.name }} ({{ employee.salary}}) </li> </ul> |
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:-
1 2 3 4 5 6 | <ul *ngFor="let employee of employees; let i = index"> <li class="text-success">{{i}}. {{ employee.name }} ({{ employee.salary}}) </li> </ul> |
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:-
1 2 3 4 5 6 | <ul *ngFor="let employee of employees; trackBy:id"> <li class="text-success">{{i}}. {{ employee.name }} ({{ employee.salary}}) </li> </ul> |
Thanks!!
I’m a full-stack developer. My hobby and profession to write blog and programming tips that helps to others. I am a great admirer of PHP, Laravel, Codeigniter, AngularJS, Vue.js, Javascript, JQuery, WordPress, Plugin Development, Theme Development and Bootstrap from the early stage.