Ad

Group Chats By Date Using Ionic

- 1 answer

I have an ionic-firebase chat application and I want to group my chats by date the way WhatsApp does, so there's a tag at the top of chats for "today", "yesterday", etc. All messages have a timestamp but I need a way to use them to group the messages. Thanks.

     this.chatService.markAsSeen();
     this.allMessages = [];
     this.allMessages = this.chatService.matchMessages;
   })```

```   <ion-list no-lines>
     <ion-item
       no-lines
       *ngFor="let item of allMessages; let i = index"
       text-wrap
     >

       <div class="bubble me" *ngIf="item.sentBy === match.uid">
         <h3 class="line-breaker">{{ item.message }}</h3>
         <p class="time-me">{{ item.time }}</p>
       </div>

       <div class="bubble you" *ngIf="item.sentBy != match.uid">
         <h3 class="line-breaker">{{ item.message }}</h3>
         <p class="time-you">{{ item.time }}</p>
       </div>
       <div
         class="seen"
         *ngIf="item[matchUid] == 0 && item.sentBy !== match.uid"
       >
         Seen
       </div>

     </ion-item>
   </ion-list>```
Ad

Answer

We've got the same thing in our chat app. For the HTML, put within your ion-item:

  <ion-row *ngIf="isDifferentDay(index)">
      <ion-badge>{{getMessageDate(index)}}</ion-badge>
    </ion-row>

Then the typescript:

 private isDifferentDay(messageIndex: number): boolean {

    if (messageIndex === 0) return true;

    const d1 = new Date(this.allMessages[messageIndex - 1].date);
    const d2 = new Date(this.allMessages[messageIndex].date);

    return d1.getFullYear() !== d2.getFullYear()
      || d1.getMonth() !== d2.getMonth()
      || d1.getDate() !== d2.getDate();
}

 private getMessageDate(messageIndex: number): string {

   const wholeDate = new Date(this.allMessages[messageIndex].date).toDateString();

   this.messageDateString = wholeDate.slice(0, wholeDate.length - 5);

   return this.messageDateString;

 }

You're welcome :)

Ad
source: stackoverflow.com
Ad