How to make chat app in ionic

This tutorial we’re going to create simple Ionic chat app with firebase backend

Technologies used:

  • Ionic Framework
  • Firebase (we’re not going to use AngularFire)

Creating a new project in Firebase

First, we need to create a new project in firebase

Step 1: Log in with your Firebase (https://firebase.google.com) & create a new project

Step 2: Click “add firebase to your web app” & get keys

Step 3: Add Rules with your database

{
  "rules": {
  ".read": "auth == null", 
  ".write": "auth == null"
  }
}

Add a rule

Note: we changed authentication to null; so anyone can access to your database

Creating Ionic Project

Once we created a project from firebase, we can set up a new Ionic project for our chat application

Create a new Ionic project

ionic start ionicfirechat blank

Change your working directory

cd ionicfirechat

Add your platform (if required)

ionic platform add android
ionic platform add ios

Installing & Setup Firebase (app.component.ts)

Add firebase node_modules to your project

npm install firebase --save

import firebase in app.component.ts

import * as firebase from 'firebase';

Add configuration to app.component.ts; Replace with your Firebase Configuration

let config = {
  apiKey: “YOUR_APIKEY”,
  authDomain: “YOUR_AUTH_DOMAIN”,
  databaseURL: “YOUR_DATABASE_URL",
  projectId: “YOUR_PROJECT_ID”,
  storageBucket: “YOUR_STORAGE_BUCKET”,
  };
firebase.initializeApp(config);

Creating UI for chat (home.html)

<ion-header>
    <ion-navbar>
        <ion-title>
            Ionic 2 Firebase Chat
        </ion-title>
    </ion-navbar>
</ion-header>
<ion-content padding>
    <ion-list no-lines>
        <ion-item *ngFor="let message of messagesList">
            <h3>{{message.name}}</h3>
            <p>{{message.message}}</p>
        </ion-item>
    </ion-list>
</ion-content>
<ion-footer>
    <ion-item>
        <ion-input type="text" placeholder="type here..." [(ngModel)]="newmessage"></ion-input>
        <button ion-button clear item-right (click)="send()">Send</button>
    </ion-item>
</ion-footer>

We’re getting username in a prompt box inside ionicViewDidLoad()

this.alert.create({
title:'Username', 
inputs:[{

  name:'username', 
  placeholder: 'username'

}], 
buttons:[{

  text: 'Continue', 
  handler: username =>this.name = username
}]
}).present();

Sending Messages to Firebase

When user clicks send button we need to call send() to insert messages into firebase & clear existing messages

send(){
  this.ref.push({
    name: this.name.username, 
    message: this.newmessage
  }); 
}

Reading Messages from Firebase

When the user-created a new message, we need to display inside <ion-content>

this.ref.on('value', data => {
    let tmp = [];
    data.forEach(data => {
        tmp.push({
            key: data.key,
            name: data.val().name,
            message: data.val().message
        })
    });
    this.messagesList = tmp;
});