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:
2
3
4
5
6
7
8
10
11
12
13
14
15
16
32
33
34
35
36
37
38
39
40
41
import { Observable } from "rxjs";
import { Chat } from "api/models/whatsapp-models";
import { Chats, Messages } from "api/collections/whatsapp-collections";
import { NavController } from "ionic-angular";
@Component({
templateUrl: 'chats.html'
...some lines skipped...
export class ChatsPage implements OnInit {
chats;
constructor(private navCtrl: NavController) {
}
...some lines skipped...
).zone();
}
showMessages(chat): void {
this.navCtrl.push(MessagesPage, {chat});
}
removeChat(chat: Chat): void {
this.chats = this.chats.map<Chat[]>(chatsArray => {
const chatIndex = chatsArray.indexOf(chat);
And let's register the click event in the view:
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">
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
:
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/whatsapp-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:
4
5
6
7
8
9
10
11
12
13
14
15
16
17
21
22
23
24
25
26
27
28
import { TabsPage } from '../pages/tabs/tabs';
import { ChatsPage } from "../pages/chats/chats";
import { MomentModule } from "angular2-moment";
import { MessagesPage } from "../pages/messages/messages";
@NgModule({
declarations: [
MyApp,
ChatsPage,
TabsPage,
MessagesPage
],
imports: [
IonicModule.forRoot(MyApp),
...some lines skipped...
entryComponents: [
MyApp,
ChatsPage,
TabsPage,
MessagesPage
],
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}]
})
Now we can complete our ChatsPage
's navigation method by importing the MessagesPage
:
3
4
5
6
7
8
9
import { Chat } from "api/models/whatsapp-models";
import { Chats, Messages } from "api/collections/whatsapp-collections";
import { NavController } from "ionic-angular";
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:
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
import { Component, OnInit } from "@angular/core";
import { NavParams } from "ionic-angular";
import { Chat, Message } from "api/models/whatsapp-models";
import { Messages } from "api/collections/whatsapp-collections";
import { Observable} from "rxjs";
@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:
11
12
13
14
15
16
chatId?: string;
content?: string;
createdAt?: Date;
ownership?: string;
}
}
Now that we have a basic component, let's implement a messages view as well:
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="settings-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="message-wrapper">
<div [class]="'message message-' + message.ownership">
<div class="message-content">{{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 list of messages to show all available messages in the selected chat. To complete the view, let's write its belonging stylesheet:
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
.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 -15px 99px !important;
}
.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: 236px;
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/4a48a2fba2ff720b4dd7c903cd9ac68522aff7c7/src/assets/chat-background.jpg
src/assets$ wget https://github.com/Urigo/Ionic2CLI-Meteor-WhatsApp/raw/4a48a2fba2ff720b4dd7c903cd9ac68522aff7c7/src/assets/message-mine.png
src/assets$ wget https://github.com/Urigo/Ionic2CLI-Meteor-WhatsApp/raw/4a48a2fba2ff720b4dd7c903cd9ac68522aff7c7/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:
18
19
20
21
22
23
24
<div *ngFor="let message of messages | async" class="message-wrapper">
<div [class]="'message message-' + message.ownership">
<div class="message-content">{{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 which would be 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:
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)="sendMessage()">
<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:
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
}
}
}
.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:
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
import { Chat, Message } from "api/models/whatsapp-models";
import { Messages } from "api/collections/whatsapp-collections";
import { Observable} from "rxjs";
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.sendMessage();
}
}
sendMessage(): void {
MeteorObservable.call('addMessage', this.selectedChat._id, this.message).zone().subscribe(() => {
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 server/imports/methods/methods.ts
file in our server and implement the method's logic:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { Meteor } from 'meteor/meteor';
import {Chats, Messages} from "../collections/whatsapp-collections";
export function initMethods() {
Meteor.methods({
addMessage(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()
})
}
}
});
}
Let's import it and call the initialization function in the main server file:
1
2
3
4
5
6
7
8
9
10
11
import * as moment from "moment";
import { Meteor } from 'meteor/meteor';
import { initMethods } from "./methods";
import { Chats, Messages } from "../collections/whatsapp-collections";
Meteor.startup(() => {
initMethods();
if (Chats.find({}).cursor.count() === 0) {
let chatId;
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 this package in the server:
api$ meteor add check
And we're gonna use it in the addMessage
method we've just defined:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { Meteor } from 'meteor/meteor';
import { Chats, Messages } from "../collections/whatsapp-collections";
import { check, Match } from "meteor/check";
const nonEmptyString = Match.Where((str) => {
check(str, String);
return str.length > 0;
});
export function initMethods() {
Meteor.methods({
addMessage(chatId: string, content: string) {
check(chatId, nonEmptyString);
check(content, nonEmptyString);
const chatExists = !!Chats.collection.find(chatId).count();
if (!chatExists) throw new Meteor.Error('chat-not-exists',
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:
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
57
58
59
60
61
62
63
64
65
66
67
68
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import {Component, OnInit, OnDestroy, ElementRef} from "@angular/core";
import { NavParams } from "ionic-angular";
import { Chat, Message } from "api/models/whatsapp-models";
import { Messages } from "api/collections/whatsapp-collections";
import { Observable } from "rxjs";
import { MeteorObservable } from "meteor-rxjs";
@Component({
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;
constructor(navParams: NavParams, element: ElementRef) {
this.selectedChat = <Chat>navParams.get('chat');
this.title = this.selectedChat.title;
this.picture = this.selectedChat.picture;
}
private get messagesPageContent(): Element {
return document.querySelector('.messages-page-content');
}
private get messagesPageFooter(): Element {
return document.querySelector('.messages-page-footer');
}
private get messagesList(): Element {
return this.messagesPageContent.querySelector('.messages');
}
private get messageEditor(): HTMLInputElement {
return <HTMLInputElement>this.messagesPageFooter.querySelector('.message-editor');
}
private get scroller(): Element {
return this.messagesList.querySelector('.scroll-content');
}
ngOnInit() {
let isEven = false;
...some lines skipped...
return messages;
});
this.autoScroller = this.autoScroll();
}
ngOnDestroy() {
this.autoScroller.disconnect();
}
onInputKeypress({keyCode}: KeyboardEvent): void {
...some lines skipped...
this.message = '';
});
}
autoScroll(): MutationObserver {
const autoScroller = new MutationObserver(this.scrollDown.bind(this));
autoScroller.observe(this.messagesList, {
childList: true,
subtree: true
});
return autoScroller;
}
scrollDown(): void {
this.scroller.scrollTop = this.scroller.scrollHeight;
this.messageEditor.focus();
}
}
Why didn't we update the scrolling position on a Meter computation? That's 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.
{{{nav_step prev_step="https://angular-meteor.com/tutorials/whatsapp2/ionic/1.0.0/meteor-server-side" next_step="https://angular-meteor.com/tutorials/whatsapp2/ionic/1.0.0/authentication"}}}