For example: I need to output a list. Each item will have a (click) handler with item object like parameter.
<ul>
<li *ngFor="let item of myList">
<button (click)="clickHandler(item)"></button>
</li>
</ul>
This list will be updated dynamically quite often: I will load new items onScroll, or filter the list by search.
For each item Angular adds an event listener!
Question:
It can be a lot of items in the list, so a lot of eventListeners will be connected and disconnected all the time.
Is there a way to apply delegation pattern to have only one eventListener live?
You can use trackBy
to improve perforamnce.
<ul>
<li *ngFor="let item of myList; trackBy: trackByFn">
<button (click)="clickHandler(item)"></button>
</li>
</ul>
trackByFn(index, item) {
return index; // or item.id
}
Angular can track which items have been added or removed according to the unique identifier and create or destroy only the items that changed when you change your collection.
You also can dive into Event delegation
in JS
.
Event delegation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With