Angular ngFor trackBy

preview_player
Показать описание
Text version of the video

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.

Slides

Angular 2 Tutorial playlist

Angular 2 Text articles and slides

All Dot Net and SQL Server Tutorials in English

All Dot Net and SQL Server Tutorials in Arabic

In this video we will discuss
1. Using trackyBy with ngFor directive
2. How to get the index of an item in a collection
3. Identifying the first and the last elements in a collection
4. Identifying even and odd elements in a collection

Using trackyBy with ngFor directive :
ngFor directive may perform poorly with large lists
A small change to the list like, adding a new item or removing an existing item may trigger a cascade of DOM manipulations

The constructor() initialises the employees property with 4 employee objects
getEmployees() method returns another list of 5 employee objects (The 4 existing employees plus a new employee object)

[table]
[thead]
[tr]

[/tr]
[/thead]
[tbody]
[tr *ngFor='let employee of employees']

[/tr]
[td colspan="5"]
No employees to display
[/td]
[/tr]
[/tbody]
[/table]
[br /]
[button (click)='getEmployees()']Refresh Employees[/button]

1. At the moment we are not using trackBy with ngFor directive
2. When the page initially loads we see the 4 employees
3. When we click "Refresh Employees" button we see the fifth employee as well
4. It looks like it just added the additional row for the fifth employee. That's not true, it effectively teared down all the [tr] and [td] elements of all the employees and recreated them.
5. To prove this launch browser developer tools by pressing F12.
6. Click on the "Elements" tab and expand the [table] and then [tbody] elements
7. At this point click the "Refresh Emplyees" button and you will notice all the [tr] elements are briefly highlighted indicating they are teared down and recreated.

This happens because Angular by defualt keeps track of objects using the object references. When we click the "Refresh Employees" button we get different object references and as a result Angular has no choice but to tear down all the old DOM elements and insert the new DOM elements.

trackByEmpCode(index: number, employee: any): string {
}

[tr *ngFor='let employee of employees; trackBy:trackByEmpCode']

At this point, run the application and lauch developer tools. When you click "Refresh Employees" first time, only the the row of the fifth employee is highlighted indicating only that[tr] element is added. On subsequent clicks, nothing is highlighted meaning none of the [tr] elements are teared down or added as the employees collection has not changed. Even now we get different object references when we click "Refresh Employees" button, but as Angular is now tracking employee objects using the employee code instead of object references, the respective DOM elements are not affected.

How to get the index of an item in a collection : In the example below, we are using the index property of the NgFor directive to store the index in a template input variable "i". The variable is then used in the [td] element where we want to display the index. We used the let keyword to create the template input variable "i".

The index of an element is extremely useful when creating the HTML elements dynamically. We will discuss creating HTML elements dynamically in our upcoming videos.

[tr *ngFor='let employee of employees; let i=index']

Identifying the first and the last element in a collection : Use the first and last properties of the ngFor directive to find if an element is the first or last element respectively.
Рекомендации по теме
Комментарии
Автор

I used this in my project and its working perfectly. Thanks a ton Venkat sir.

sammyyou
Автор

In the last, at 11:22 time of the video, the headings ("Is Even" and "Is Last") got wrongly placed. A minor correction, I searched in the comments, it seems nobody noticed. Your videos are a great start for any beginner and a source of revision of concepts.

rubbalbhusri
Автор

your English 50 times better than English of your Indian friends on freeCodeCamp and Udemy, thank u for clear speech

eugenenovikov
Автор

Its like people standing in Queue for iPhone in US / for Rajanikant movie in India. I m standing in queue for Venkat's Videos. I don't know my no in queue.

niluniverse
Автор

This is awesome Thanks Sir. Really helpful for me. Please make a video to call the APIs in angular 2.

nirajrajpurohit
Автор

HI Venkat,
Thank you for the tutorial. Your series on angular are great. I have a doubt regarding the trackBy, that if any value of one of the object changes, then it won't be updated on DOM, as we are not refreshing already loaded DOM. Could you help tackling such scenarios?


Thank you
Deep

dvishal
Автор

Hi Sir,
Your tutorials are amazing and very helpful. I have a small query in this lesson.

You have said that when we trackby in ngfor, then the previous columns will not be loaded again.
In ngFor we have a last attribute, that specifies the last element.

when we initially have 4 elements, the fourth element is treated as the last element, but when we add the fifth element, then the boolean value for the fourth element representing last should be made it to false and the fifth element should say it as true

Please confirm whether it will happen?

kinglikeking
Автор

Hi Venkat in the trackByEmpCode method, why do we need those parameters, index and employee. I tried running the code with out those parameters and it worked as expected, i.e with out refreshing the table elements. Infact I even made the return type as Void, it still worked. All the trackBy function would need is an empty method, to work, I think.

prakashgunjari
Автор

thanks for all the pain/efforts you took, for this video.

laughandtune
Автор

short, simple, and clear, thank you

satheshkumar
Автор

You are simply great Thanks alot... This is soooo generous that u have given the notes as well I mean I cannot explain I am soo greatful to you

SUMITKAUSHIK
Автор

Thanks for uploading this, it very nice, seen and implemented, thanks @Venkat :) Be Blessed

mohsinazamafridi
Автор

empty method also return the same value like not reloading the <tr>
trackByEmpCode() {
}

Not sure about those two parameter, why we have to use that
trackByEmpCode(index:number, employee:any):string {
return employee.code;
}

please explain
Thanks in advance

selvarajmunuswamy
Автор

hi
can we use index property of ngFor directly for interpolation instead of declaring varible

shridharjjoshi
Автор

your tutorials are amazing, sir really i like it sir, i am ur fan

dipakranjansahoo
Автор

Hello, your tutorials are amazing! But your old tutorials (Java Script, Entity Framework etc.) used Web Forms. Today it's not longer relevant. Can you do similar tutorials using newer technologies (MVC, Web Api)

antonoreshko
Автор

Dear Venkat, I would like to ask for the trackByEmpCode method how come you didn't pass any value for both the index and employee parameters from trackBy:trackByEmpCode specified with the ngFor directive ???

trackByEmpCode(index:number, employee: any): string {
    return employee.code;
}

ymtan
Автор

hey Venkat, i have the following question but in ASP.NET Web API
what if we want to make the response be like TotalCount, TotalPages and Entity Details so if we used HttpResponseMessage or IHttpActionResult the response will be Entity Details and other details like StatusCode Header etc so where we can add TotalCount and TotalPages??
also if we added the TotalCount and TotalPages in Class called XResponse along with the Entity Properties and make the Method return type XResponse in this case we can not control in the Status Code or Headers or anything that related to HttpResponseMessage?

mamdouhemara
Автор

Ur Angular 2 videos r very useful for me thank u sir

krish_techaadimulam
Автор

Although the tr elements are not being recreated every time after trackBy, but the selector tag of the component is getting refreshed. So indirectly the table is also being recreated ?

abhishektiwari