Fork me on GitHub

WhatsApp Clone with Meteor and Ionic 2 CLI

Socially Merge Version (Last Update: 2017-02-01)

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:

6.1 Add showMessages src/pages/chats/chats.ts
1
2
3
4
5
6
7
 
10
11
12
13
14
15
16
 
31
32
33
34
35
36
37
38
39
40
import { Component, OnInit } from '@angular/core';
import { Chats, Messages } from 'api/collections';
import { Chat } from 'api/models';
import { NavController } from 'ionic-angular';
import { Observable } from 'rxjs';
 
@Component({
...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 src/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 src/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 'api/models';
 
@Component({
  selector: 'messages-page',
  template: `Messages Page`
})
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 src/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 src/pages/chats/chats.ts
3
4
5
6
7
8
9
import { Chat } from 'api/models';
import { NavController } from 'ionic-angular';
import { Observable } from 'rxjs';
import { MessagesPage } from '../messages/messages';
 
@Component({
  templateUrl: 'chats.html'

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 src/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
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { Component, OnInit } from '@angular/core';
import { NavParams } from 'ionic-angular';
import { Chat, Message } from 'api/models';
import { Observable } from 'rxjs';
import { Messages } from 'api/collections';
 
@Component({
  selector: 'messages-page',
  templateUrl: 'messages.html'
})
export class MessagesPage implements OnInit {
  selectedChat: Chat;
  title: string;
  picture: string;
  messages: Observable<Message[]>;
 
  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 api/server/models.ts
15
16
17
18
19
  content?: string;
  createdAt?: Date;
  type?: MessageType
  ownership?: string;
}

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

6.8 Add message page template src/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 src/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 src/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;
    }
  }
}

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

src/assets$ wget https://github.com/Urigo/Ionic2CLI-Meteor-WhatsApp/raw/cc8a09a04e26b50395b703092fb15cb07aec36ce/src/assets/chat-background.jpg
src/assets$ wget https://github.com/Urigo/Ionic2CLI-Meteor-WhatsApp/raw/cc8a09a04e26b50395b703092fb15cb07aec36ce/src/assets/message-mine.png
src/assets$ wget https://github.com/Urigo/Ionic2CLI-Meteor-WhatsApp/raw/cc8a09a04e26b50395b703092fb15cb07aec36ce/src/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:

6.11 Use amDateFormat src/pages/messages/messages.html
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 src/pages/messages/messages.html
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    </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 src/pages/messages/messages.scss
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    }
  }
}
 
.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 src/pages/messages/messages.ts
1
2
3
4
5
6
7
8
9
 
14
15
16
17
18
19
20
 
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 { Chat, Message, MessageType } from 'api/models';
import { Observable } from 'rxjs';
import { Messages } from 'api/collections';
import { MeteorObservable } from 'meteor-rxjs';
 
@Component({
  selector: 'messages-page',
...some lines skipped...
  title: string;
  picture: string;
  messages: Observable<Message[]>;
  message: string = '';
 
  constructor(navParams: NavParams) {
    this.selectedChat = <Chat>navParams.get('chat');
...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 addMessage, 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 api/server/methods.ts file in our server and implement the method's logic:

6.15 Implement Meteor method for adding a new message api/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 { Chats } from './collections/chats';
import { Messages } from './collections/messages';
import { MessageType } from './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.17 Use check to add validations api/server/methods.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { Chats } from './collections/chats';
import { Messages } from './collections/messages';
import { MessageType } from './models';
import { check, Match } from 'meteor/check';
 
const nonEmptyString = Match.Where((str) => {
  check(str, String);
  return str.length > 0;
});
 
Meteor.methods({
  addMessage(type: MessageType, chatId: string, content: string) {
    check(type, Match.OneOf(String, [ MessageType.TEXT ]));
    check(chatId, nonEmptyString);
    check(content, nonEmptyString);
 
    const chatExists = !!Chats.collection.find(chatId).count();
 
    if (!chatExists) {

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 src/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, OnInit, OnDestroy, ElementRef } from '@angular/core';
import { NavParams } from 'ionic-angular';
import { Chat, Message, MessageType } from 'api/models';
import { Observable } from 'rxjs';
...some lines skipped...
  selector: 'messages-page',
  templateUrl: 'messages.html'
})
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 src/pages/messages/messages.ts
1
2
3
4
5
6
7
8
9
10
 
14
15
16
17
18
19
20
 
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
import { Component, OnInit, OnDestroy, ElementRef } from '@angular/core';
import { NavParams } from 'ionic-angular';
import { Chat, Message, MessageType } from 'api/models';
import { Messages } from 'api/collections';
import { MeteorObservable } from 'meteor-rxjs';
import * as moment from 'moment';
import { _ } from 'meteor/underscore';
 
@Component({
  selector: 'messages-page',
...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 src/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>