簡體   English   中英

如何在 Angular 中使用 *ngFor 提高渲染性能

[英]How to improve rendering performance with *ngFor in Angular

我正在創建一個聊天應用程序,當一次發送大量消息時性能很慢。 消息顯示,但 UI 有一段時間沒有響應。 這是代碼的簡化版本,我該如何解決?

HTML:

<div class="message-notification" *ngFor="let newMessage of chatMessages"; trackBy: trackByMsgs>
   <custom-notification [incomingChat]="newMessage" (dismissedEvent)="onDismiss($event)" (closedEvent)="onNotifcationClose($event)"></custom-notification>
</div>

TS:

newChatMessages: any[];

constructor(private chatService: ChatService) {}

 ngOnInit() {
    this.chatService.chatMsg.subscribe((msg:any) => {
    if (msg) {
       this.activatePopup(msg);
    }
  }

  activatePopup(message) {
    if (message.msgId !== null && message.title !== null) {
       this.setTitle(message);

    //If popup is already open then do not display a duplicate popup for the same message
         let index = this.isPopupOpen(message);
         if (index === -1) {
           newChatMessages.push(message);
         }else {
           newChatMessages[index] = message;
         }
     }
  }

   trackByMsgs(index:number, msg:any) {
     return msg.msgId && msg.title;
   }

   isPopUpOpen(message){
     let index = -1;
     if (this.newChatMessages){
      index = this.newChatMessages.findIndex(
         msg => msg.id === message.id && msg.title === message.title);
      }
    return index;
   }

為了幫助你,你能在 Stackblitz 中提供一個復制品嗎?

在您的情況下,最好的方法是使用OnPush Change Detection Strategy手動控制 angular 更改檢測。 您應該小心使用它,因為當它打開時,angular 只有在觸發 onChanges 生命周期或異步 pipe 收到新值時才會檢測到更改。 它也適用於所有子組件。

然后,您需要通過在組件中注入ChangeDetectorRef來手動檢測更改,並在每次要將數據更改應用於 dom 時對其調用方法 detectChanges。
閱讀這篇文章以獲得更好的理解

另一篇關於提高 angular 應用程序性能的有趣文章https://medium.com/swlh/angular-performance-optimization-techniques-5b7ca0808f8b

使用 trackBy 有助於 angular 記住 ngFor 中加載的元素,並在更改檢測時僅更新更改的一次。 但是您的trackByMsgs返回一個 boolean 這不是它應該返回的。 如果您調整 trackBy 以返回唯一鍵,例如 msg.msgId 或項目的索引,您可能會看到差異。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM