RUVIDEO
Поделитесь видео 🙏

Angular ngFor trackBy

Text version of the video
http://csharp-video-tutorials.blogspot.com/2017/07/angular-ngfor-trackby.html

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.
https://www.youtube.com/channel/UC7sEwIXM_YfAMyonQCrGfWA/?sub_confirmation=1

Slides
http://csharp-video-tutorials.blogspot.com/2017/07/angular-ngfor-trackby_13.html

Angular 2 Tutorial playlist
https://www.youtube.com/playlist?list=PL6n9fhu94yhWqGD8BuKuX-VTKqlNBj-m6

Angular 2 Text articles and slides
http://csharp-video-tutorials.blogspot.com/2017/06/angular-2-tutorial-for-beginners_12.html

All Dot Net and SQL Server Tutorials in English
https://www.youtube.com/user/kudvenkat/playlists?view=1&sort=dd

All Dot Net and SQL Server Tutorials in Arabic
https://www.youtube.com/c/KudvenkatArabic/playlists

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

For example, consider this code in employeeList.component.ts

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)

Now look at this code in employeeList.component.html
[table]
[thead]
[tr]

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

[/tr]
[tr *ngIf="!employees || employees.length==0"]
[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.

Angular can avoid this churn with trackBy. The trackBy function takes the index and the current item as arguments and returns the unique identifier by which that item should be tracked. In our case we are tracking by Employee code. Add this method to employeeList.component.ts.

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

Make the following change in employeeList.component.html : Notice along with ngFor we also specified trackBy

[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.

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Angular ngFor trackBy», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.