Fork me on GitHub

WhatsApp Clone with Meteor and Ionic 2 CLI

Ionic 3 Version (Last Update: 2017-06-15)

Chats page

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

First Ionic Component

Now that we're finished with the initial setup, we can start building our app.

An application created by Ionic's CLI will have a very clear methodology. The app is made out of pages, each page is made out of 3 files:

  • .html - A view template file written in HTML based on Angular 2's new template engine.
  • .scss - A stylesheet file written in a CSS pre-process language called SASS.
  • .ts - A script file written in Typescript.

By default, the application will be created with the home page. Since our app's flow doesn't contain it, we first gonna clean it up by running the following command:

$ rm -rf src/pages/home

Second, we will remove its declaration in the app module:

2.2 Removed tabs components from the module declaration src/app/app.module.ts
5
6
7
8
9
10
11
12
13
14
 
16
17
18
19
20
21
22
import { StatusBar } from '@ionic-native/status-bar';
 
import { MyApp } from './app.component';
 
@NgModule({
  declarations: [
    MyApp
  ],
  imports: [
    BrowserModule,
...some lines skipped...
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [
    StatusBar,

Now, let's create our new Component, we'll call it ChatsPage:

2.3 Create Chats page component src/pages/chats/chats.ts
1
2
3
4
5
6
7
8
9
10
import { Component } from '@angular/core';
 
@Component({
  templateUrl: 'chats.html'
})
export class ChatsPage {
  constructor() {
 
  }
}

Angular 2 uses decorators to declare Components, and we use ES2016 classes to create the actual component, and the templateUrl declares the template file for the component. So now let's create this template file, next to the component file:

2.4 Added chats page template src/pages/chats/chats.html
1
2
3
4
5
6
7
8
9
10
11
<ion-header>
  <ion-navbar>
    <ion-title>
      Chats
    </ion-title>
  </ion-navbar>
</ion-header>
 
<ion-content padding>
  Hello!
</ion-content>

Once creating an Ionic page it's recommended to use the following layout:

  • <ion-header> - The header of the page. Will usually contain content that should be bounded to the top like navbar.
  • <ion-content> - The content of the page. Will usually contain it's actual content like text.
  • <ion-footer> - The footer of the page. Will usually contain content that should be bounded to the bottom like toolbars.

Now, we need to add a declaration for this new Component in our NgModule definition:

2.5 Add chats page to the NgModule src/app/app.module.ts
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
18
19
20
21
22
23
24
25
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { ChatsPage } from '../pages/chats/chats';
 
import { MyApp } from './app.component';
 
@NgModule({
  declarations: [
    MyApp,
    ChatsPage
  ],
  imports: [
    BrowserModule,
...some lines skipped...
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    ChatsPage
  ],
  providers: [
    StatusBar,

You can read more about Angular 2 NgModule here.

We will define the ChatsPage as the initial component of our app by setting the rootPage property in the main app component:

2.6 Use the chats page as the main root page src/app/app.component.ts
2
3
4
5
6
7
8
9
10
11
12
13
14
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { ChatsPage } from '../pages/chats/chats';
 
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = ChatsPage;
 
  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
    platform.ready().then(() => {

Let's add some code to our Component with a simple logic; Once the component is created we gonna define some dummy chats, using the Observable.of, so we can have some data to test our view against:

2.7 Add stubs for chats objects src/pages/chats/chats.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
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
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import * as moment from 'moment';
 
@Component({
  templateUrl: 'chats.html'
})
export class ChatsPage {
  chats: Observable<any[]>;
 
  constructor() {
    this.chats = this.findChats();
  }
 
  private findChats(): Observable<any[]> {
    return Observable.of([
      {
        _id: '0',
        title: 'Ethan Gonzalez',
        picture: 'https://randomuser.me/api/portraits/thumb/men/1.jpg',
        lastMessage: {
          content: 'You on your way?',
          createdAt: moment().subtract(1, 'hours').toDate()
        }
      },
      {
        _id: '1',
        title: 'Bryan Wallace',
        picture: 'https://randomuser.me/api/portraits/thumb/lego/1.jpg',
        lastMessage: {
          content: 'Hey, it\'s me',
          createdAt: moment().subtract(2, 'hours').toDate()
        }
      },
      {
        _id: '2',
        title: 'Avery Stewart',
        picture: 'https://randomuser.me/api/portraits/thumb/women/1.jpg',
        lastMessage: {
          content: 'I should buy a boat',
          createdAt: moment().subtract(1, 'days').toDate()
        }
      },
      {
        _id: '3',
        title: 'Katie Peterson',
        picture: 'https://randomuser.me/api/portraits/thumb/women/2.jpg',
        lastMessage: {
          content: 'Look at my mukluks!',
          createdAt: moment().subtract(4, 'days').toDate()
        }
      },
      {
        _id: '4',
        title: 'Ray Edwards',
        picture: 'https://randomuser.me/api/portraits/thumb/men/2.jpg',
        lastMessage: {
          content: 'This is wicked good ice cream.',
          createdAt: moment().subtract(2, 'weeks').toDate()
        }
      }
    ]);
  }
}

Further explanation regards RxJS can be found in step 3

moment is an essential package for our data fabrication, which requires us to install it using the following command:

$ npm install --save moment

TypeScript Interfaces

Now, because we use TypeScript, we can define our own data-types and use them in our app, which will give you a better auto-complete and developing experience in most IDEs. In our application, we have 2 models: a chat model and a message model. We will define their interfaces in a file located under the path src/models.ts:

2.9 Create models file with declarations of Chat, Message and MessageType src/models.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
export enum MessageType {
  TEXT = <any>'text'
}
 
export interface Chat {
  _id?: string;
  title?: string;
  picture?: string;
  lastMessage?: Message;
}
 
export interface Message {
  _id?: string;
  chatId?: string;
  content?: string;
  createdAt?: Date;
  type?: MessageType
}

Now that the models are up and set, we can apply them to the ChatsPage:

2.10 Use TypeScript models src/pages/chats/chats.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
21
22
23
24
25
26
27
28
 
31
32
33
34
35
36
37
38
 
41
42
43
44
45
46
47
48
 
51
52
53
54
55
56
57
58
 
61
62
63
64
65
66
67
68
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import * as moment from 'moment';
import { Chat, MessageType } from '../../models';
 
@Component({
  templateUrl: 'chats.html'
})
export class ChatsPage {
  chats: Observable<Chat[]>;
 
  constructor() {
    this.chats = this.findChats();
  }
 
  private findChats(): Observable<Chat[]> {
    return Observable.of([
      {
        _id: '0',
...some lines skipped...
        picture: 'https://randomuser.me/api/portraits/thumb/men/1.jpg',
        lastMessage: {
          content: 'You on your way?',
          createdAt: moment().subtract(1, 'hours').toDate(),
          type: MessageType.TEXT
        }
      },
      {
...some lines skipped...
        picture: 'https://randomuser.me/api/portraits/thumb/lego/1.jpg',
        lastMessage: {
          content: 'Hey, it\'s me',
          createdAt: moment().subtract(2, 'hours').toDate(),
          type: MessageType.TEXT
        }
      },
      {
...some lines skipped...
        picture: 'https://randomuser.me/api/portraits/thumb/women/1.jpg',
        lastMessage: {
          content: 'I should buy a boat',
          createdAt: moment().subtract(1, 'days').toDate(),
          type: MessageType.TEXT
        }
      },
      {
...some lines skipped...
        picture: 'https://randomuser.me/api/portraits/thumb/women/2.jpg',
        lastMessage: {
          content: 'Look at my mukluks!',
          createdAt: moment().subtract(4, 'days').toDate(),
          type: MessageType.TEXT
        }
      },
      {
...some lines skipped...
        picture: 'https://randomuser.me/api/portraits/thumb/men/2.jpg',
        lastMessage: {
          content: 'This is wicked good ice cream.',
          createdAt: moment().subtract(2, 'weeks').toDate(),
          type: MessageType.TEXT
        }
      }
    ]);

Ionic's Theming System

Ionic 2 provides us with a comfortable theming system which is based on SASS variables. The theme definition file is located in src/theme/variable.scss. Since we want our app to have a "Whatsappish" look, we will define a new SASS variable called whatsapp in the variables file:

2.11 Add whatsapp color to the app theme src/theme/variables.scss
38
39
40
41
42
43
44
45
  secondary:  #32db64,
  danger:     #f53d3d,
  light:      #f4f4f4,
  dark:       #222,
  whatsapp:   #075E54
);
 
 

The whatsapp color can be used by adding an attribute called color with a value whatsapp to any Ionic component.

To begin with, we can start by implementing the ChatsView and apply our newly defined theme into it. This view will contain a list representing all the available chats in the component's data-set:

2.12 Add the layout of the chats page src/pages/chats/chats.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
26
27
28
29
30
31
32
33
34
35
36
<ion-header>
  <ion-navbar color="whatsapp">
    <ion-title>
      Chats
    </ion-title>
    <ion-buttons end>
      <button ion-button icon-only class="add-chat-button">
        <ion-icon name="person-add"></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 class="chats-page-content">
  <ion-list class="chats">
    <ion-item-sliding *ngFor="let chat of chats | async">
      <button ion-item class="chat">
        <img class="chat-picture" [src]="chat.picture">
        <div class="chat-info">
          <h2 class="chat-title">{{chat.title}}</h2>
 
          <span *ngIf="chat.lastMessage" class="last-message">
            <p *ngIf="chat.lastMessage.type == 'text'" class="last-message-content last-message-content-text">{{chat.lastMessage.content}}</p>
            <span class="last-message-timestamp">{{chat.lastMessage.createdAt }}</span>
          </span>
        </div>
      </button>
      <ion-item-options class="chat-options">
        <button ion-button color="danger" class="option option-remove">Remove</button>
      </ion-item-options>
    </ion-item-sliding>
  </ion-list>
</ion-content>

We use ion-list which Ionic translates into a list, and we use ion-item to represent a single item in that list. A chat item includes an image, the receiver's name, and its recent message.

The async pipe is used to iterate through data which should be fetched asynchronously, in this case, observables.

Now, in order to finish our theming and styling, let's create a stylesheet file for our component:

2.13 Create SCSS file for chats page src/pages/chats/chats.scss
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
.chats-page-content {
  .chat-picture {
    border-radius: 50%;
    width: 50px;
    float: left;
  }
 
  .chat-info {
    float: left;
    margin: 10px 0 0 20px;
 
    .last-message-timestamp {
      position: absolute;
      top: 10px;
      right: 10px;
      font-size: 14px;
      color: #9A9898;
    }
  }
}

Ionic will load newly defined stylesheet files automatically, so you shouldn't be worried for importations.

External Angular 2 Modules

Since Ionic 2 uses Angular 2 as the layer view, we can load Angular 2 modules just like any other plain Angular 2 application. One module that may come in our interest would be the angular2-moment module, which will provide us with the ability to use moment's utility functions in the view as pipes.

It requires us to install angular2-moment module using the following command:

$ npm install --save angular2-moment

Now we will need to declare this module in the app's main component:

2.15 Import MomentModule into our app module src/app/app.module.ts
3
4
5
6
7
8
9
 
15
16
17
18
19
20
21
22
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { MomentModule } from 'angular2-moment';
import { ChatsPage } from '../pages/chats/chats';
 
import { MyApp } from './app.component';
...some lines skipped...
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    MomentModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [

Which will make moment available as a pack of pipes, as mentioned earlier:

2.16 Use amCalendar pipe src/pages/chats/chats.html
24
25
26
27
28
29
30
 
          <span *ngIf="chat.lastMessage" class="last-message">
            <p *ngIf="chat.lastMessage.type == 'text'" class="last-message-content last-message-content-text">{{chat.lastMessage.content}}</p>
            <span class="last-message-timestamp">{{ chat.lastMessage.createdAt | amCalendar }}</span>
          </span>
        </div>
      </button>

Ionic Touch Events

Ionic provides us with components which can handle mobile events like: slide, tap and pinch. Since we're going to take advantage of the "sliding" event in the chats view, we used the ion-item-sliding component, so any time we will slide our item to the left, we should see a Remove button.

Right now this button is not hooked to anything. It requires us to bind it into the component:

2.17 Add remove chat event src/pages/chats/chats.html
29
30
31
32
33
34
35
        </div>
      </button>
      <ion-item-options class="chat-options">
        <button ion-button color="danger" class="option option-remove" (click)="removeChat(chat)">Remove</button>
      </ion-item-options>
    </ion-item-sliding>
  </ion-list>

And now that it is bound to the component we can safely implement its handler:

2.18 Implement removeChat method src/pages/chats/chats.ts
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
      }
    ]);
  }
 
  removeChat(chat: Chat): void {
    this.chats = this.chats.map((chatsArray: Chat[]) => {
      const chatIndex = chatsArray.indexOf(chat);
      if (chatIndex !== -1) {
        chatsArray.splice(chatIndex, 1);
      }
 
      return chatsArray;
    });
  }
}