NgForOf performance
Since NgForOf generates HTML based on collection elements, it is notorious for causing performance issues. But we cannot blame the directive. It does what it is supposed to do: iterate and generate elements! If the underlying collection is huge, UI rendering can take a performance hit, especially if the collection changes too often. The cost of continuously destroying and creating elements in response to a changing collection can quickly become prohibitive.
One of the performance tweaks for NgForOf allows us to alter the behavior of ngForOf when it comes to creating and destroying DOM elements (when the underlying collection elements are added or removed).
Imagine a scenario where we frequently get an array of objects from the server and bind it to the view using NgForOf. The default behavior of NgForOf is to regenerate the DOM every time we refresh the list (since Angular does a standard object equality check). However, as developers, we may very well know not much has changed. Some new objects may have been added, some removed, and maybe some modified. But Angular just regenerates the complete DOM.
To alleviate this situation, Angular allows us to specify a custom tracking function, which lets Angular know when two objects being compared are equal. Have a look at the following function:
trackByUserId(index: number, hero: User) { return user.id; }
A function such as this can be used in the NgForOf template to tell Angular to compare the user object based on its id property instead of doing a reference equality check.
This is how we then use the preceding function in the NgForOf template:
<div *ngFor="let user of users; trackBy: trackByUserId">{{user.name}}</div>
NgForOf will now avoid recreating DOM for users with IDs already rendered.
Remember, Angular may still update the existing DOM elements if the bound properties of a user have changed.
That's enough on the ngFor directive; let's move ahead.
We still need to understand the role of the safeVideoUrls and the OnChange life cycle events in the VideoPlayerComponent implementation. Let's tackle the former first and understand the need for safeVideoUrls.