Fork me on GitHub

WhatsApp Clone with Ionic 2 and Meteor CLI

Socially Merge Version (Last Update: 14.02.2017)

Messages Page

Note: If you skipped ahead to this section, click here to download a zip of the tutorial at this point.

In this step we will add the messages view and the ability to send messages.

Before we implement anything related to the messages pages, we first have to make sure that once we click on a chat item in the chats page, we will be promoted into its corresponding messages view. Let's first implement the showMessages() method in the chats component:

1
2
3
4
5
 
12
13
14
15
16
17
18
 
33
34
35
36
37
38
39
40
41
42
43
44
import { Component, OnInit } from '@angular/core';
import { NavController } from 'ionic-angular';
import * as Moment from 'moment';
import { Observable } from 'rxjs';
import { Chats, Messages } from '../../../../imports/collections';
...some lines skipped...
export class ChatsPage implements OnInit {
  chats;
 
  constructor(private navCtrl: NavController) {
  }
 
  ngOnInit() {
...some lines skipped...
      ).zone();
  }
 
  showMessages(chat): void {
    this.navCtrl.push(MessagesPage, {chat});
  }
 
  removeChat(chat: Chat): void {
    Chats.remove({_id: chat._id}).subscribe(() => {
    });
  }
}

And let's register the click event in the view:

6.2 Bind click event to showMessages client/imports/pages/chats/chats.html
17
18
19
20
21
22
23
<ion-content class="chats-page-content">
  <ion-list class="chats">
    <ion-item-sliding *ngFor="let chat of chats | async">
      <button ion-item class="chat" (click)="showMessages(chat)">
        <img class="chat-picture" [src]="chat.picture">
        <div class="chat-info">
          <h2 class="chat-title">{{chat.title}}</h2>

Notice how we used a controller called NavController. The NavController is Ionic's new method to navigate in our app. We can also use a traditional router, but since in a mobile app we have no access to the url bar, this might come more in handy. You can read more about the NavController here.

Let's go ahead and implement the messages component. We'll call it MessagesPage:

6.3 Create a stub MessagesPage component client/imports/pages/messages/messages.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { Component, OnInit } from '@angular/core';
import { NavParams } from 'ionic-angular';
import { Chat } from '../../../../imports/models';
import template from './messages.html';
 
@Component({
  template
})
export class MessagesPage implements OnInit {
  selectedChat: Chat;
 
  constructor(navParams: NavParams) {
    this.selectedChat = <Chat>navParams.get('chat');
 
    console.log('Selected chat is: ', this.selectedChat);
  }
 
  ngOnInit() {
 
  }
}

As you can see, in order to get the chat's id we used the NavParams service. This is a simple service which gives you access to a key-value storage containing all the parameters we've passed using the NavController.

For more information about the NavParams service, see the following link.

Don't forget that any component you create has to be imported in the app's module:

6.4 Import MessagesPage in the NgModule client/imports/app/app.module.ts
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
18
19
20
21
22
23
24
25
import { MomentModule } from 'angular2-moment';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { ChatsPage } from '../pages/chats/chats'
import { MessagesPage } from '../pages/messages/messages';
import { MyApp } from './app.component';
 
@NgModule({
  declarations: [
    MyApp,
    ChatsPage,
    MessagesPage
  ],
  imports: [
    IonicModule.forRoot(MyApp),
...some lines skipped...
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    ChatsPage,
    MessagesPage
  ],
  providers: [
    { provide: ErrorHandler, useClass: IonicErrorHandler }

Now we can complete our ChatsPage's navigation method by importing the MessagesPage:

6.5 Import MessagesPage to chats page client/imports/pages/chats/chats.ts
4
5
6
7
8
9
10
import { Observable } from 'rxjs';
import { Chats, Messages } from '../../../../imports/collections';
import { Chat, MessageType } from '../../../../imports/models';
import { MessagesPage } from '../messages/messages';
import template from './chats.html';
 
@Component({

We're missing some important details in the messages page. We don't know who we're chatting with, we don't know how does he look like, and we don't know which message is ours, and which is not. We can add these using the following code snippet:

6.6 Add basic messages component client/imports/pages/messages/messages.ts
1
2
3
4
5
6
7
 
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { Component, OnInit } from '@angular/core';
import { NavParams } from 'ionic-angular';
import { Messages } from '../../../../imports/collections';
import { Chat, Message } from '../../../../imports/models';
import template from './messages.html';
 
@Component({
...some lines skipped...
  constructor(navParams: NavParams) {
    this.selectedChat = <Chat>navParams.get('chat');
 
    this.title = this.selectedChat.title;
    this.picture = this.selectedChat.picture;
  }
 
  ngOnInit() {
    let isEven = false;
 
    this.messages = Messages.find(
      {chatId: this.selectedChat._id},
      {sort: {createdAt: 1}}
    ).map((messages: Message[]) => {
      messages.forEach((message: Message) => {
        message.ownership = isEven ? 'mine' : 'other';
        isEven = !isEven;
      });
 
      return messages;
    });
  }
}

Since now we're not really able to determine the author of a message, we mark every even message as ours; But later on once we have an authentication system and users, we will be filling the missing gap.

We will also have to update the message model to have an ownership property:

6.7 Add ownership property to messages model imports/models.ts
14
15
16
17
18
19
  chatId?: string;
  content?: string;
  createdAt?: Date;
  ownership?: string;
  type?: MessageType;
}

Now that we have a basic component, let's implement a messages view as well:

6.8 Add message page template client/imports/pages/messages/messages.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<ion-header>
  <ion-navbar color="whatsapp" class="messages-page-navbar">
    <ion-buttons>
      <img class="chat-picture" [src]="picture">
    </ion-buttons>
 
    <ion-title class="chat-title">{{title}}</ion-title>
 
    <ion-buttons end>
      <button ion-button icon-only class="attach-button"><ion-icon name="attach"></ion-icon></button>
      <button ion-button icon-only class="options-button"><ion-icon name="more"></ion-icon></button>
    </ion-buttons>
  </ion-navbar>
</ion-header>
 
<ion-content padding class="messages-page-content">
  <ion-scroll scrollY="true" class="messages">
    <div *ngFor="let message of messages | async" class="day-wrapper">
        <div [class]="'message message-' + message.ownership">
          <div *ngIf="message.type == 'text'" class="message-content message-content-text">{{message.content}}</div>
          <span class="message-timestamp">{{ message.createdAt }}</span>
      </div>
    </div>
  </ion-scroll>
</ion-content>

The template consists of a picture and a title inside the navigation bar. It also has two buttons. The purpose of the first button from the left would be sending attachments, and the second one should show an options pop-over, just like in the chats page. As for the content, we simply used a list of messages to show all available messages in the selected chat. To complete the view, let's write its belonging stylesheet:

6.9 Style the message component client/imports/pages/messages/messages.html
15
16
17
18
19
20
21
 
<ion-content padding class="messages-page-content">
  <ion-scroll scrollY="true" class="messages">
    <div *ngFor="let message of messages | async" class="message-wrapper">
        <div [class]="'message message-' + message.ownership">
          <div *ngIf="message.type == 'text'" class="message-content message-content-text">{{message.content}}</div>
          <span class="message-timestamp">{{ message.createdAt }}</span>
6.9 Style the message component client/imports/pages/messages/messages.scss
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
.messages-page-navbar {
  .chat-picture {
    width: 50px;
    border-radius: 50%;
    float: left;
  }
 
  .chat-title {
    line-height: 50px;
    float: left;
  }
}
 
.messages-page-content {
  > .scroll-content {
    margin: 42px -16px 42px !important;
  }
 
  .day-wrapper .day-timestamp {
    margin-left: calc(50% - 64px);
    margin-right: calc(50% - 64px);
    margin-bottom: 9px;
    text-align: center;
    line-height: 27px;
    height: 27px;
    border-radius: 3px;
    color: gray;
    box-shadow: 0 1px 2px rgba(0, 0, 0, .15);
    background: #d9effa;
  }
 
  .messages {
    height: 100%;
    background-image: url(/assets/chat-background.jpg);
    background-color: #E0DAD6;
    background-repeat: no-repeat;
    background-size: cover;
  }
 
  .message-wrapper {
    margin-bottom: 9px;
 
    &::after {
      content: "";
      display: table;
      clear: both;
    }
  }
 
  .message {
    display: inline-block;
    position: relative;
    max-width: 65vh;
    border-radius: 7px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, .15);
 
    &.message-mine {
      float: right;
      background-color: #DCF8C6;
 
      &::before {
        right: -11px;
        background-image: url(/assets/message-mine.png)
      }
    }
 
    &.message-other {
      float: left;
      background-color: #FFF;
 
      &::before {
        left: -11px;
        background-image: url(/assets/message-other.png)
      }
    }
 
    &.message-other::before, &.message-mine::before {
      content: "";
      position: absolute;
      bottom: 3px;
      width: 12px;
      height: 19px;
      background-position: 50% 50%;
      background-repeat: no-repeat;
      background-size: contain;
    }
 
    .message-content {
      padding: 5px 7px;
      word-wrap: break-word;
 
      &::after {
        content: " \00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0";
        display: inline;
      }
    }
 
    .message-timestamp {
      position: absolute;
      bottom: 2px;
      right: 7px;
      font-size: 12px;
      color: gray;
    }
  }
}
6.9 Style the message component client/main.scss
5
6
7
8
9
@import "imports/app/app";
 
// Pages
@import "imports/pages/chats/chats";
@import "imports/pages/messages/messages";

This style requires us to add some assets. So inside the public/assets dir, download the following:

public/assets$ wget https://github.com/Urigo/Ionic2CLI-Meteor-WhatsApp/raw/master/public/assets/chat-background.jpg
public/assets$ wget https://github.com/Urigo/Ionic2CLI-Meteor-WhatsApp/raw/master/public/assets/message-mine.png
public/assets$ wget https://github.com/Urigo/Ionic2CLI-Meteor-WhatsApp/raw/master/public/assets/message-other.png

Now we need to take care of the message's timestamp and format it, then again we gonna use angular2-moment only this time we gonna use a different format using the amDateFormat pipe:

18
19
20
21
22
23
24
    <div *ngFor="let message of messages | async" class="message-wrapper">
        <div [class]="'message message-' + message.ownership">
          <div *ngIf="message.type == 'text'" class="message-content message-content-text">{{message.content}}</div>
          <span class="message-timestamp">{{ message.createdAt | amDateFormat: 'HH:mm' }}</span>
      </div>
    </div>
  </ion-scroll>

Our messages are set, but there is one really important feature missing: sending messages. Let's implement our message editor. We will start with the view itself. We will add an input for editing our messages, a send button, and a record button whose logic won't be implemented in this tutorial since we only wanna focus on the text messaging system. To fulfill this layout we gonna use a tool-bar (ion-toolbar) inside a footer (ion-footer) and place it underneath the content of the view:

6.12 Add message editor to messages view template client/imports/pages/messages/messages.html
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
      </div>
    </div>
  </ion-scroll>
</ion-content>
 
<ion-footer>
  <ion-toolbar color="whatsapp" class="messages-page-footer" position="bottom">
    <ion-input [(ngModel)]="message" (keypress)="onInputKeypress($event)" class="message-editor" placeholder="Type a message"></ion-input>
 
    <ion-buttons end>
      <button ion-button icon-only *ngIf="message" class="message-editor-button" (click)="sendTextMessage()">
        <ion-icon name="send"></ion-icon>
      </button>
 
      <button ion-button icon-only *ngIf="!message" class="message-editor-button">
        <ion-icon name="mic"></ion-icon>
      </button>
    </ion-buttons>
  </ion-toolbar>
</ion-footer>

Our stylesheet requires few adjustments as well:

6.13 Add styles for message page footer client/imports/pages/messages/messages.scss
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
      color: gray;
    }
  }
}
 
.messages-page-footer {
  padding-right: 0;
 
  .message-editor {
    margin-left: 2px;
    padding-left: 5px;
    background: white;
    border-radius: 3px;
  }
 
  .message-editor-button {
    box-shadow: none;
    width: 50px;
    height: 50px;
    font-size: 17px;
    margin: auto;
  }
}

Now we can implement the handler for messages sending in the component:

6.14 Implement sendTextMessage method client/imports/pages/messages/messages.ts
1
2
3
4
5
6
7
8
9
 
11
12
13
14
15
16
17
18
19
20
21
22
23
 
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { Component, OnInit } from '@angular/core';
import { NavParams } from 'ionic-angular';
import { MeteorObservable } from 'meteor-rxjs';
import { Observable } from 'rxjs';
import { Messages } from '../../../../imports/collections';
import { Chat, Message, MessageType } from '../../../../imports/models';
import template from './messages.html';
 
@Component({
...some lines skipped...
})
export class MessagesPage implements OnInit {
  selectedChat: Chat;
  title: string;
  picture: string;
  messages: Observable<Message[]>;
  message: string = '';
 
  constructor(navParams: NavParams) {
    this.selectedChat = <Chat>navParams.get('chat');
    this.title = this.selectedChat.title;
    this.picture = this.selectedChat.picture;
  }
...some lines skipped...
      return messages;
    });
  }
 
  onInputKeypress({ keyCode }: KeyboardEvent): void {
    if (keyCode === 13) {
      this.sendTextMessage();
    }
  }
 
  sendTextMessage(): void {
    // If message was yet to be typed, abort
    if (!this.message) {
      return;
    }
 
    MeteorObservable.call('addMessage', MessageType.TEXT,
      this.selectedChat._id,
      this.message
    ).zone().subscribe(() => {
      // Zero the input field
      this.message = '';
    });
  }
}

As you can see, we've used a Meteor method called sendTextMessage, which is yet to exist. This method will add messages to our messages collection and run on both client's local cache and server. Now we're going to create a server/methods.ts file in our server and implement the method's logic:

6.15 Implement Meteor method for adding a new message server/methods.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { Meteor } from 'meteor/meteor';
import { Chats, Messages } from '../imports/collections';
import { MessageType } from '../imports/models';
 
Meteor.methods({
  addMessage(type: MessageType, chatId: string, content: string) {
    const chatExists = !!Chats.collection.find(chatId).count();
 
    if (!chatExists) {
      throw new Meteor.Error('chat-not-exists',
        'Chat doesn\'t exist');
    }
 
    return {
      messageId: Messages.collection.insert({
        chatId: chatId,
        content: content,
        createdAt: new Date(),
        type: type
      })
    };
  }
});

We would also like to validate some data sent to methods we define. For this we're gonna use a utility package provided to us by Meteor and it's called check.

It requires us to add the following package in the server:

api$ meteor add check

And we're gonna use it in the addMessage method we've just defined:

6.15 Implement Meteor method for adding a new message server/methods.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { Meteor } from 'meteor/meteor';
import { Chats, Messages } from '../imports/collections';
import { MessageType } from '../imports/models';
 
Meteor.methods({
  addMessage(type: MessageType, chatId: string, content: string) {
    const chatExists = !!Chats.collection.find(chatId).count();
 
    if (!chatExists) {
      throw new Meteor.Error('chat-not-exists',
        'Chat doesn\'t exist');
    }
 
    return {
      messageId: Messages.collection.insert({
        chatId: chatId,
        content: content,
        createdAt: new Date(),
        type: type
      })
    };
  }
});

Auto Scroll

In addition, we would like the view to auto-scroll down whenever a new message is added. We can achieve that using a native class called MutationObserver, which can detect changes in the view:

6.18 Implement auto scroll client/imports/pages/messages/messages.ts
1
2
3
4
 
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
 
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { Component, OnDestroy, OnInit, ElementRef } from '@angular/core';
import { NavParams } from 'ionic-angular';
import { MeteorObservable } from 'meteor-rxjs';
import { Observable } from 'rxjs';
...some lines skipped...
@Component({
  template
})
export class MessagesPage implements OnInit, OnDestroy {
  selectedChat: Chat;
  title: string;
  picture: string;
  messages: Observable<Message[]>;
  message: string = '';
  autoScroller: MutationObserver;
  scrollOffset = 0;
 
  constructor(
    navParams: NavParams,
    private el: ElementRef
  ) {
    this.selectedChat = <Chat>navParams.get('chat');
    this.title = this.selectedChat.title;
    this.picture = this.selectedChat.picture;
  }
 
  private get messagesPageContent(): Element {
    return this.el.nativeElement.querySelector('.messages-page-content');
  }
 
  private get messagesList(): Element {
    return this.messagesPageContent.querySelector('.messages');
  }
 
  private get scroller(): Element {
    return this.messagesList.querySelector('.scroll-content');
  }
 
  ngOnInit() {
    this.autoScroller = this.autoScroll();
 
    let isEven = false;
 
    this.messages = Messages.find(
...some lines skipped...
    });
  }
 
  ngOnDestroy() {
    this.autoScroller.disconnect();
  }
 
  autoScroll(): MutationObserver {
    const autoScroller = new MutationObserver(this.scrollDown.bind(this));
 
    autoScroller.observe(this.messagesList, {
      childList: true,
      subtree: true
    });
 
    return autoScroller;
  }
 
  scrollDown(): void {
    // Scroll down and apply specified offset
    this.scroller.scrollTop = this.scroller.scrollHeight - this.scrollOffset;
    // Zero offset for next invocation
    this.scrollOffset = 0;
  }
 
  onInputKeypress({ keyCode }: KeyboardEvent): void {
    if (keyCode === 13) {
      this.sendTextMessage();

So why didn't we update the scrolling position on a Meteor computation? - Because we want to initiate the scrolling function once the view is ready, not the data. They might look similar, but the difference is crucial.

Group Messages

Our next goal would be grouping our messages on the view according to the day they were sent, with an exception of the current date. So let's say we're in January 2nd 2017; Messages from yesterday will appear above the label January 1 2017.

We can group our messages right after being fetched by the Observable using the map function:

6.19 Add group by date to the UI client/imports/pages/messages/messages.ts
1
2
3
4
5
6
7
8
 
15
16
17
18
19
20
21
 
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { Component, OnDestroy, OnInit, ElementRef } from '@angular/core';
import { NavParams } from 'ionic-angular';
import { MeteorObservable } from 'meteor-rxjs';
import { _ } from 'meteor/underscore';
import * as Moment from 'moment';
import { Observable } from 'rxjs';
import { Messages } from '../../../../imports/collections';
import { Chat, Message, MessageType } from '../../../../imports/models';
...some lines skipped...
  selectedChat: Chat;
  title: string;
  picture: string;
  messagesDayGroups;
  message: string = '';
  autoScroller: MutationObserver;
  scrollOffset = 0;
...some lines skipped...
 
  ngOnInit() {
    this.autoScroller = this.autoScroll();
    this.subscribeMessages();
  }
 
  ngOnDestroy() {
    this.autoScroller.disconnect();
  }
 
  subscribeMessages() {
    this.scrollOffset = this.scroller.scrollHeight;
    this.messagesDayGroups = this.findMessagesDayGroups();
  }
 
  findMessagesDayGroups() {
    let isEven = false;
 
    return Messages.find({
      chatId: this.selectedChat._id
    }, {
      sort: { createdAt: 1 }
    })
      .map((messages: Message[]) => {
        const format = 'D MMMM Y';
 
        // Compose missing data that we would like to show in the view
        messages.forEach((message) => {
          message.ownership = isEven ? 'mine' : 'other';
          isEven = !isEven;
 
          return message;
        });
 
        // Group by creation day
        const groupedMessages = _.groupBy(messages, (message) => {
          return Moment(message.createdAt).format(format);
        });
 
        // Transform dictionary into an array since Angular's view engine doesn't know how
        // to iterate through it
        return Object.keys(groupedMessages).map((timestamp: string) => {
          return {
            timestamp: timestamp,
            messages: groupedMessages[timestamp],
            today: Moment().format(format) === timestamp
          };
        });
      });
  }
 
  autoScroll(): MutationObserver {
    const autoScroller = new MutationObserver(this.scrollDown.bind(this));
 

And now we will add a nested iteration in the messages view; The outer loop would iterate through the messages day-groups, and the inner loop would iterate through the messages themselves:

6.20 Update the template to use grouped messages client/imports/pages/messages/messages.html
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 
<ion-content padding class="messages-page-content">
  <ion-scroll scrollY="true" class="messages">
    <div *ngFor="let day of messagesDayGroups | async" class="day-wrapper">
      <div *ngFor="let message of day.messages" class="message-wrapper">
        <div [class]="'message message-' + message.ownership">
          <div *ngIf="message.type == 'text'" class="message-content message-content-text">{{message.content}}</div>
          <span class="message-timestamp">{{ message.createdAt | amDateFormat: 'HH:mm' }}</span>
        </div>
      </div>
 
      <div *ngIf="!day.today" class="day-timestamp">{{day.timestamp}}</div>
    </div>
  </ion-scroll>
</ion-content>

{{{nav_step prev_step="https://angular-meteor.com/tutorials/whatsapp2/meteor/folder-structure" next_step="https://angular-meteor.com/tutorials/whatsapp2/meteor/authentication"}}}