Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: delegation pattern. The way to optimise handlers inside ngFor

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?

like image 950
Smiranin Avatar asked Jun 09 '17 08:06

Smiranin


1 Answers

You can use trackBy to improve perforamnce.

app.component.html

<ul>
    <li *ngFor="let item of myList; trackBy: trackByFn">
          <button (click)="clickHandler(item)"></button>       
    </li>
</ul>

app.component.ts

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

like image 108
Alexander Avatar answered Nov 05 '22 15:11

Alexander