Ionic 4 and Angular 6 Tutorial: Firebase Realtime CRUD Mobile App

by Didin J. on Aug 16, 2018 Ionic 4 and Angular 6 Tutorial: Firebase Realtime CRUD Mobile App

A comprehensive step by step tutorial on build Ionic 4, Angular 6, Cordova and Firebase Realtime CRUD (Create, Read, Update, Delete) Mobile App

Ionic 4 and Angular 6 Tutorial: build Firebase Realtime CRUD (Create, Read, Update, Delete) Mobile App. In this Ionic 4 and Angular 6 tutorial will show you how to access the Firebase Real-time Database. Not just accessing but run CRUD (Create, Read, Update, Delete) operation for populating Firebase Real-time Database.

Shortcut to the steps:

Previously, we have created a lot of Firebase tutorial with Ionic Framework before like below:

What we build here just the Ionic 4, Angular 6 and Firebase CRUD app for Bulletin Board which just create information then show the list of information in the home page of the app. There also details of information, edit and delete the bulletin board information. The following tools, frameworks, and modules are required for this tutorial:

  1. Node.js
  2. Ionic 4
  3. Angular 6
  4. Firebase NPM Module
  5. Firebase/Google Account
  6. Terminal or Node.js Command Line
  7. IDE or Text Editor

Before moving to the steps, make sure you have installed the latest Node.js and Ionic 4. To check it, type this command in the terminal or Node.js command line.

node -v
v8.11.1
npm -v
6.2.0
ionic -v
Ionic CLI PRO 4.0.2
cordova -v
7.1.0

That's the last version when this tutorial was written. For update Node.js and it's `npm` download from Node.js https://nodejs.org and choose the recommended version. For Ionic 4, type this command.

sudo npm i -D -E ionic@latest
sudo npm i -g cordova


Setup Firebase

Go to console.firebase.google.com and log in using your Google account.

Ionic 4 and Angular 6 Tutorial: Firebase Realtime CRUD Mobile App - Firebase Welcome

Click CREATE NEW PROJECT button, name it as you like (ours: BulletinBoard) and choose your country. Finally, click CREATE PROJECT button.

Ionic 4 and Angular 6 Tutorial: Firebase Realtime CRUD Mobile App - Firebase Project Overview

Go to Develop menu then choose Database then scroll to `Or choose Real-time Database` then click `Create Database`.

Ionic 4 and Angular 6 Tutorial: Firebase Realtime CRUD Mobile App - Firebase Security Rules

Choose `Start in test mode` then click `Enabled` button.

Ionic 4 and Angular 6 Tutorial: Firebase Realtime CRUD Mobile App - Firebase Real-time Database

Now, the Firebase Real-time Database is ready to use.


Create a New Ionic Angular App

To create a new Ionic 4 / Angular 6 app, type this command.

ionic start ionic-firebase-crud blank --type=angular

You will see questions during the installation, just type `N` for now. Next, go to the newly created app folder.

cd ./ionic-firebase-crud

For sanitizing, run the app on the browser for the first time to make sure everything working properly.

ionic serve -l

Type `Y` if asked to install `@ionic/lab`. Now, the browser will open automatically then you will see this Ionic 4 Lab page.

Ionic 4 and Angular 6 Tutorial: Firebase Realtime CRUD Mobile App - Ionic 4 Serve


Install and Configure the Firebase Module

Firebase library ship with NPM module. For that, type this command to install the module.

npm install --save firebase

Next, register the Firebase module in the Ionic 4 / Angular 6 app by open and edit this file `src/app.component.ts` then add this import of Firebase.

import * as firebase from 'firebase';

Declare a constant variable for holds Firebase setting before `@Component` that contain the configuration variable for accessing Firebase using apiKey, authDomain, databaseURL, projectId, storageBucket.

const config = {
  apiKey: 'YOUR_APIKEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  databaseURL: 'YOUR_DATABASE_URL',
  projectId: 'YOUR_PROJECT_ID',
  storageBucket: 'YOUR_STORAGE_BUCKET',
};

Add this line inside the `initializeApp` function for running the Firebase configuration.

initializeApp() {
  this.platform.ready().then(() => {
    this.statusBar.styleDefault();
    this.splashScreen.hide();
  });
  firebase.initializeApp(config);
}

Now, Firebase database is ready to populate.


Add List of Bulletin Board

We will use existing Ionic 4 / Angular 6 home page for display the list of the bulletin board. Open and edit `src/app/home/home.page.ts` then add these imports of AlertController (@ionic/angular), Router, ActivatedRoute (@angular/router), and Firebase.

import { AlertController } from '@ionic/angular';
import { Router, ActivatedRoute } from '@angular/router';
import * as firebase from 'Firebase';

Declare variables before the constructor for hold bulletin board list and referencing Firebase database.

infos = [];
ref = firebase.database().ref('infos/');

Add this Firebase function to listening to any value changes from Firebase Database then extract the response to an array using the next function.

constructor(public router: Router, public loadingController: LoadingController) {
  this.ref.on('value', resp => {
    this.infos = [];
    this.infos = snapshotToArray(resp);
  });
}

Add this constant function below the Class block for converting Firebase response to an array.

export const snapshotToArray = snapshot => {
    let returnArr = [];

    snapshot.forEach(childSnapshot => {
        let item = childSnapshot.val();
        item.key = childSnapshot.key;
        returnArr.push(item);
    });

    return returnArr;
};

Add a function under the constructor for navigating to `add-info` page.

addInfo() {
  this.router.navigate(['/add-info']);
}

Add a function for edit info data.

edit(key) {
  this.router.navigate(['/edit/'+key]);
}

Add an asynchronous function for delete info data.

async delete(key) {
  const alert = await this.alertController.create({
    header: 'Confirm!',
    message: 'Are you sure want to delete this info?',
    buttons: [
      {
        text: 'Cancel',
        role: 'cancel',
        cssClass: 'secondary',
        handler: (blah) => {
          console.log('cancel');
        }
      }, {
        text: 'Okay',
        handler: () => {
          firebase.database().ref('infos/'+key).remove();
        }
      }
    ]
  });

  await alert.present();
}

Finally, open and edit `src/app/home/home.page.html` then replace all tags with this <ion-content> that contain <ion-list> with an array of data.

<ion-header>
  <ion-toolbar>
    <ion-title>
      Info List
    </ion-title>
    <ion-buttons slot="end">
      <ion-button routerLink="/create"><ion-icon name="add-circle"></ion-icon></ion-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-list>
    <ion-item-sliding *ngFor="let info of infos">
      <ion-item detail lines="full" routerLink="/detail/{{info.key}}">
        <ion-icon name="desktop" slot="start"></ion-icon>
        {{info.info_title}}
      </ion-item>
      <ion-item-options side="end">
        <ion-item-option color="primary" (click)="edit(info.key)">EDIT</ion-item-option>
        <ion-item-option color="danger" (click)="delete(info.key)">DELETE</ion-item-option>
      </ion-item-options>
    </ion-item-sliding>
  </ion-list>
</ion-content>


Add Page for Create Bulletin Board Info

To create a new Angular 6 page, we use Ionic 4 CLI to generate it. Type this command for generating it.

ionic g page create

Next, open and edit `src/app/create.module.ts` then add or modify this import to add `ReactiveFormsModule`.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

Add this `ReactiveFormsModule` to `@NgModule` imports.

imports: [
  CommonModule,
  FormsModule,
  IonicModule,
  ReactiveFormsModule,
  RouterModule.forChild(routes)
],

Next, open and edit `src/app/create/create.page.ts` then add these imports of ActivatedRoute, Router, FormControl, FormGroupDirective, FormBuilder, NgForm, Validators, and FormArray (Angular Forms).

import * as firebase from 'Firebase';
import { ActivatedRoute, Router  } from '@angular/router';
import { FormControl, FormGroupDirective, FormBuilder, FormGroup, NgForm, Validators, FormArray } from '@angular/forms';

Inject that modules to the constructor params.

constructor(private route: ActivatedRoute,
  public router: Router,
  private formBuilder: FormBuilder) { }

Add these variables before the constructor.

ref = firebase.database().ref('infos/');
infoForm: FormGroup;

Initialize the info FormBuilder inside the constructor body.

constructor(private route: ActivatedRoute,
  public router: Router,
  private formBuilder: FormBuilder) {
    this.infoForm = this.formBuilder.group({
      'info_title' : [null, Validators.required],
      'info_description' : [null, Validators.required]
    });
  }

Next, add the function to post the form data to the Firebase Real-time Database.

saveInfo() {
  let newInfo = firebase.database().ref('infos/').push();
  newInfo.set(this.infoForm.value);
  this.router.navigate(['/detail/'+newInfo.key]);
}

Finally, open and edit `src/app/create/create.page.html` then replace all HTML 5 tags with this.

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button></ion-back-button>
    </ion-buttons>
    <ion-title>Create Info</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
  <form [formGroup]="infoForm">
    <ion-item>
      <ion-label position="floating">Info Title</ion-label>
      <ion-input type="text" formControlName="info_title"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label position="floating">Info Description</ion-label>
      <ion-input type="text" formControlName="info_description"></ion-input>
    </ion-item>
    <ion-button shape="round" color="primary" expand="block" [disabled]="!infoForm.valid" (click)="saveInfo()">Save</ion-button>
  </form>
</ion-content>


Add Page for Show Bulletin Board Info Detail

Create a new Ionic 4 / Angular 6 page by type this command to generate it.

ionic g page detail

Open and edit `src/app/detail/detail.page.ts` then add these imports of Firebase, ActivatedRoute, and Router.

import * as firebase from 'Firebase';
import { ActivatedRoute, Router  } from '@angular/router';

Inject that module to the constructor.

constructor(private route: ActivatedRoute,
  public router: Router) { }

Declare a variable before the constructor.

info = {};

Load info data from Firebase Realtime Database to the body of the constructor.

constructor(private route: ActivatedRoute,
  public router: Router) {
  firebase.database().ref('infos/'+this.route.snapshot.paramMap.get('key')).on('value', resp => {
    this.info = snapshotToObject(resp);
  });
}

Create this class for converting Firebase Real-time Database response to the Angular 6 object.

export const snapshotToObject = snapshot => {
  let item = snapshot.val();
  item.key = snapshot.key;

  return item;
}

Finally, open and edit `src/app/detail/detail.page.html` then replace all HTML tags with this.

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button></ion-back-button>
    </ion-buttons>
    <ion-title>Info Details</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
  <ion-card>
    <ion-card-content>
      <ion-card-title>{{info.info_title}}</ion-card-title>

      <p>{{info.info_description}}</p>
    </ion-card-content>
  </ion-card>
</ion-content>


Add Page for Edit Bulletin Board Info

Create a new Ionic 4 / Angular 6 page by type this command for generating it.

ionic g page edit

Next, open and edit `src/app/edit.module.ts` then add or modify this import to add `ReactiveFormsModule`.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

Add this `ReactiveFormsModule` to `@NgModule` imports.

imports: [
  CommonModule,
  FormsModule,
  IonicModule,
  ReactiveFormsModule,
  RouterModule.forChild(routes)
],

Open and edit `src/app/edit/edit.page.ts` then add these imports of the required Angular Router and Forms.

import * as firebase from 'Firebase';
import { ActivatedRoute, Router  } from '@angular/router';
import { FormControl, FormGroupDirective, FormBuilder, FormGroup, NgForm, Validators, FormArray } from '@angular/forms';

Inject that module to the constructor.

constructor(private route: ActivatedRoute,
  public router: Router,
  private formBuilder: FormBuilder) { }

Declare a variable before the constructor.

ref = firebase.database().ref('infos/');
infoForm: FormGroup;

Create a function for load info data based on the key that gets from params.

getInfo(key) {
  firebase.database().ref('infos/'+key).on('value', resp => {
    let info = snapshotToObject(resp);
    this.infoForm.controls['info_title'].setValue(info.info_title);
    this.infoForm.controls['info_description'].setValue(info.info_description);
  });
}

Call that function after initializing the FormGroup to the body of the constructor.

constructor(private route: ActivatedRoute,
  public router: Router,
  private formBuilder: FormBuilder) {
    this.infoForm = this.formBuilder.group({
      'info_title' : [null, Validators.required],
      'info_description' : [null, Validators.required]
    });
    this.getInfo(this.route.snapshot.paramMap.get('key'));
  }

Create this class for converting Firebase Real-time Database response to the Angular 6 object.

export const snapshotToObject = snapshot => {
  let item = snapshot.val();
  item.key = snapshot.key;

  return item;
}

Add this function to update the data from the FormGroup to the Firebase Real-time Database.

updateInfo() {
  let newInfo = firebase.database().ref('infos/'+this.route.snapshot.paramMap.get('key')).update(this.infoForm.value);
  this.router.navigate(['/detail/'+this.route.snapshot.paramMap.get('key')]);
}

Finally, open and edit `src/app/edit/edit.page.html` then replace all HTML tags with this.

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button></ion-back-button>
    </ion-buttons>
    <ion-title>Edit Info</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
  <form [formGroup]="infoForm">
    <ion-item>
      <ion-label position="floating">Info Title</ion-label>
      <ion-input type="text" formControlName="info_title"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label position="floating">Info Description</ion-label>
      <ion-input type="text" formControlName="info_description"></ion-input>
    </ion-item>
    <ion-button shape="round" color="primary" expand="block" [disabled]="!infoForm.valid" (click)="updateInfo()">Update</ion-button>
  </form>
</ion-content>


Run and Test the Ionic 4, Angular 6, and Firebase Realtime App

This is the time to show what we have built so far. The Ionic 4, Angular 6 and Firebase CRUD mobile apps. Type this command to run this app in the browser.

ionic serve -l

And here we go, just test all of the CRUD function of this Ionic 4, Angular 6 and Firebase app.

Ionic 4 and Angular 6 Tutorial: Firebase Realtime CRUD Mobile App - Info List
Ionic 4 and Angular 6 Tutorial: Firebase Realtime CRUD Mobile App - Create Info
Ionic 4 and Angular 6 Tutorial: Firebase Realtime CRUD Mobile App - Info Details

To run on the device, type this series of commands.

ionic cordova platform rm android
ionic cordova platform add android
ionic cordova platform rm ios
ionic cordova platform add ios
ionic cordova run android
ionic cordova run ios

That it's, the Ionic 4, Angular 6 and Firebase CRUD mobile apps. You can get the working full source code in our GitHub.

We know that building beautifully designed Ionic apps from scratch can be frustrating and very time-consuming. Check Ion2FullApp ELITE - The Complete Ionic 3 Starter App and save development and design time.

That just the basic. If you need more deep learning about Ionic, Angular, and Typescript, you can find the following books:

Or take the following course:

Thanks!

Loading…