简体   繁体   中英

Angular2: Enhance the performance of scroll event with a big ngFor List

I'm developing a web chat, the structute of the chat shows the messages like this:

<div class="scrollable" (scroll)="detectTop($event)">
    <div class="message-ballon" *ngfor="message in messages">
        <span class="time-chat" *ngIf="showTime(message)"> {{message.time}} </span>
        <p class="message-content"> {{message.content}} </p>
     </div>
</div>

My detectTop(e) function checks if scrollTop === 0 if yes it get more messages from server and updates messages with it.

My showTime function compares the message with the messages above it to check if it is the same date.

The problem is the app is painfully slow, without the scroll event the scrolls works ok and is very fast.

I really want to increase the performance, but I'm not figuring how.

There is a faster way to detect scrollTop event and not impact so much on performance?

This problem is big even with small 10 messages list, and with more than 100 messsages the scroll stops

try adding a tracker to the *ngFor loop:

*ngFor="let message of messages; trackBy:messageTracker

and in your JS code:

messageTracker(index, message) {
  return message? message.id : undefined;
}

this will avoid re-rendering the messages on scroll

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM