Build Ionic 4 Firebase CRUD App with Angular 8

By Digamber Rawat Last updated on
A complete step by step tutorial on creating Ionic 4, Firebase Realtime Database, Cordova and Angular 8 doctors appointment CRUD (Create, Read, Update, Delete) mobile app.

In this Ionic 4 Firebase and Angular 8 tutorial, we will learn how to build CRUD (Create, Read, Update, Delete) app. In this doctor’s appointment CRUD mobile application, we will learn how to store app data in the Firebase Real-time NoSQL Database.

Firebase is a NoSQL Realtime database based on the document-oriented model and helps in building top-notch mobile and web applications. Firebase stores and sync web and mobile app data quite smoothly. It offers tons of excellent features such as:

  • Cloud storage
  • Realtime update
  • Easy A/B Testing
  • Analytics Monitoring
  • Authentication support
  • Easy Server management
  • Real-time communication
  • Offline access to WEB SDK
  • Hosting and cloud storage
  • Push notifications support
  • Straightforward app hosting
  • Google Cloud IoT tools Integration support

Our doctor’s appointment Ionic 4 Firebase CRUD app allows us to make an appointment. User will be able to view all the appointments, update and delete the appointments. We will need the following packages, frameworks, and tools to get started with this tutorial.

  • Node
  • Ionic 4
  • Angular 8
  • Text Editor
  • Firebase Account
  • Firebase NPM Library
  • Command Line Tool or Terminal

Generate Ionic 4/Angular Project

Run the following command to generate a brand new Ionic 4 / Angular 8 app.

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

Get inside the project’s folder.

cd ionic-firebase-crud

Run the following command to install lab mode.

npm i @ionic/lab --save-dev

Start the Ionic 4 Firebase CRUD project.

ionic serve -l

Ionic 4 Angular 8 Firebase CRUD App

Configure Firebase Library in Ionic 4/Angular 8

In order to make the Firebase work in our Ionic 4 app, we must have a Firebase config key. To get the config keys, go to console.firebase.google.com and register an account and get the Firebase config keys.

If you are a beginner, then check out my detailed article on Setting up Firebase Database in Ionic 4 and Angular 8.

Install Firebase Module in Ionic 4/Angular

Install the Firebase module in Ionic 4/Angular project. Run the following command in the terminal.

npm install @angular/fire

Insert Firebase Config Keys in Ionic 4/Angular 8

Insert the Firebase config keys in both environment.prod.ts (production environment) and environment.ts files.

To store the data in the Firebase Realtime database you need to add your Firebase keys environment.prod.ts

export const environment = {
  production: true,
  firebaseConfig: {
    apiKey: "<your-api-key>",
    authDomain: "<your-auth-domain>",
    databaseURL: "<your-database-url>",
    projectId: "<your-cloud-firestore-project>",
    storageBucket: "<your-storage-bucket>",
    messagingSenderId: "<your-sender-id>",
    appId: "<your-app-id>",
    measurementId: "<your-measurement-id>"
  }
};

Add the following code inside the environment.ts file.

export const environment = {
  production: false,
  firebaseConfig: {
    apiKey: "<your-api-key>",
    authDomain: "<your-auth-domain>",
    databaseURL: "<your-database-url>",
    projectId: "<your-cloud-firestore-project>",
    storageBucket: "<your-storage-bucket>",
    messagingSenderId: "<your-sender-id>",
    appId: "<your-app-id>",
    measurementId: "<your-measurement-id>"
  }
};

Import and Register Firebase Services in Ionic 4

Now we will import and register Firebase services and environment object in the app.module.ts file.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

//  firebase imports, remove what you don't require
import { AngularFireModule } from '@angular/fire';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { AngularFireDatabaseModule } from '@angular/fire/database';
import { AngularFireStorageModule } from '@angular/fire/storage';

// environment
import { environment } from '../environments/environment';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFireAuthModule,
    AngularFireDatabaseModule,
    AngularFireStorageModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }

In this tutorial, we need only AngularFireDatabaseModule to be imported and registered in the AppModule class.

Setup Routes in Ionic 4

In order to navigate in our Ionic 4/Firebase app we need to configure routes. Run the following command to create pages in Ionic.

ng generate page make-appointment

ng generate page edit-appointment

To show the appointment list we will use the home page, the make-appointment page will be used to make the appointments. In the edit-appointment page we will edit the appointments.

Open the src/app/app-routing.ts file and add the following code to configure the routes in Ionic 4/Angular 8 app.

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)},
  {
    path: 'make-appointment',
    loadChildren: () => import('./make-appointment/make-appointment.module').then( m => m.MakeAppointmentPageModule)
  },
  {
    path: 'edit-appointment/:id',
    loadChildren: () => import('./edit-appointment/edit-appointment.module').then( m => m.EditAppointmentPageModule)
  },
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})

export class AppRoutingModule { }

Next, open the app.component.html file and add the ion-router-outlet along with Ionic bottom tabs to activate the nav items.

<ion-app>
  <ion-router-outlet></ion-router-outlet>
</ion-app>

<ion-tabs>
  <ion-tab-bar slot="bottom">
    <ion-tab-button routerLinkActive="tab-selected" routerLink="/home" class="ios" tab="home">
      <ion-icon name="list-box"></ion-icon>
      <ion-label>Appointments</ion-label>
    </ion-tab-button>

    <ion-tab-button routerLinkActive="tab-selected" routerLink="/make-appointment" class="ios" tab="make-appointment">
      <ion-icon name="add-circle"></ion-icon>
      <ion-label>Book Appointment</ion-label>
    </ion-tab-button>
  </ion-tab-bar>
</ion-tabs>

The routerLinkActive=”” tag ads the active class on the selected navigation item in Ionic 4/Angular.

The routerLink =”” tag helps in navigation from one page to another page in Ionic 4/Angular.

Create CRUD Operation with Firebase API

Create a shared folder then create Appointment.ts file inside of it.

export class Appointment {
    $key: string;
    name: string;
    email: string
    mobile: number;
}

Run the following command to create a service in Angular 8, here we will define CREATE, READ, UPDATE & DELETE operations using Firebase API.

ng generate service shared/appointment

Then, Include the following code inside shared/appointment.service.ts:

import { Injectable } from '@angular/core';
import { Appointment } from '../shared/appointment';
import { AngularFireDatabase, AngularFireList, AngularFireObject } from '@angular/fire/database';

@Injectable({
  providedIn: 'root'
})

export class AppointmentService {
  bookingListRef: AngularFireList<any>;
  bookingRef: AngularFireObject<any>;

  constructor(private db: AngularFireDatabase) { }

  // Create
  createBooking(apt: Appointment) {
    return this.bookingListRef.push({
      name: apt.name,
      email: apt.email,
      mobile: apt.mobile
    })
  }

  // Get Single
  getBooking(id: string) {
    this.bookingRef = this.db.object('/appointment/' + id);
    return this.bookingRef;
  }

  // Get List
  getBookingList() {
    this.bookingListRef = this.db.list('/appointment');
    return this.bookingListRef;
  }

  // Update
  updateBooking(id, apt: Appointment) {
    return this.bookingRef.update({
      name: apt.name,
      email: apt.email,
      mobile: apt.mobile
    })
  }

  // Delete
  deleteBooking(id: string) {
    this.bookingRef = this.db.object('/appointment/' + id);
    this.bookingRef.remove();
  }
}

Add Item to the Firebase Database in Ionic 4

We will show you how to add items to the Firebase Realtime database but first to work get the user information we need to create a form so to work with forms you must import and register ReactiveFormsModule in make-appointment.module.ts file.

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

@NgModule({
  imports: [
    ReactiveFormsModule,
    FormsModule,
  ]
})

export class MakeAppointmentPageModule { }

Next, add the following code in make-appointment.page.ts file.

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder } from "@angular/forms";
import { AppointmentService } from './../shared/appointment.service';

@Component({
  selector: 'app-make-appointment',
  templateUrl: './make-appointment.page.html',
  styleUrls: ['./make-appointment.page.scss'],
})

export class MakeAppointmentPage implements OnInit {
  bookingForm: FormGroup;

  constructor(
    private aptService: AppointmentService,
    private router: Router,
    public fb: FormBuilder
  ) { }

  ngOnInit() {
    this.bookingForm = this.fb.group({
      name: [''],
      email: [''],
      mobile: ['']
    })
  }

  formSubmit() {
    if (!this.bookingForm.valid) {
      return false;
    } else {
      this.aptService.createBooking(this.bookingForm.value).then(res => {
        console.log(res)
        this.bookingForm.reset();
        this.router.navigate(['/home']);
      })
        .catch(error => console.log(error));
    }
  }
}

To set up the form first import FormGroup and FormBuilder Reactive Forms services in Ionic 4. Define a variable with FormGroup inject the FormBuilder in the constructor and create a FormControl inside the this.bookingForm using the FormBuilder object.

Next, AppointmentService class, inject inside the constructor. Submit the form values by accessing the AppointmentService CRUD api and redirect the user to the appointments list page using Angular Router service.

Next, Use the *ngFor directive to create the appointment form using Ionic 4 UI components. Open make-appointment.page.html file and add the following code.

<ion-header>
  <ion-toolbar class="ios hydrated">
    <ion-title class="ios title-ios hydrated">Booking</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-list lines="full">
    <form [formGroup]="bookingForm" (ngSubmit)="formSubmit()">
      <ion-item>
        <ion-label position="floating">Name</ion-label>
        <ion-input formControlName="name" type="text" required></ion-input>
      </ion-item>

      <ion-item>
        <ion-label position="floating">Email</ion-label>
        <ion-input formControlName="email" type="text" required>
        </ion-input>
      </ion-item>

      <ion-item>
        <ion-label position="floating">Mobile</ion-label>
        <ion-input formControlName="mobile" type="text" required>
        </ion-input>
      </ion-item>

      <ion-row>
        <ion-col>
          <ion-button type="submit" color="primary" shape="full" expand="block">Book Appointment</ion-button>
        </ion-col>
      </ion-row>
    </form>
  </ion-list>
</ion-content>

Edit Ionic List

Delete & Display Item List

To display the list import AppointmentService and then inject in the constructor. Get the appointment list via getBookingList() function. To remove the item from the database we are using deleteBooking(id) method and passing the item id or key in it. Open home.page.ts file and add the following code.

import { Component, OnInit } from '@angular/core';
import { Appointment } from '../shared/appointment';
import { AppointmentService } from './../shared/appointment.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage implements OnInit {
  Bookings = [];

  constructor(
    private aptService: AppointmentService
  ) { }

  ngOnInit() {
    this.fetchBookings();
    let bookingRes = this.aptService.getBookingList();
    bookingRes.snapshotChanges().subscribe(res => {
      this.Bookings = [];
      res.forEach(item => {
        let a = item.payload.toJSON();
        a['$key'] = item.key;
        this.Bookings.push(a as Appointment);
      })
    })
  }

  fetchBookings() {
    this.aptService.getBookingList().valueChanges().subscribe(res => {
      console.log(res)
    })
  }

  deleteBooking(id) {
    console.log(id)
    if (window.confirm('Do you really want to delete?')) {
      this.aptService.deleteBooking(id)
    }
  }
}

To display items open home.page.html file and insert the following code in it.

<ion-header>
  <ion-toolbar>
    <ion-title>
      Doctors App
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-list class="ios list-ios hydrated">
    <ion-list-header class="ios hydrated">
      Appointments
    </ion-list-header>

    <ion-item *ngFor="let booking of Bookings" class="user-list">
      <ion-label>
        <h5>
          <ion-icon name="person"></ion-icon> {{booking.name}}
        </h5>
        <p>
          <ion-icon name="call"></ion-icon> {{booking.mobile}}
        </p>
      </ion-label>

      <div class="item-note" item-end>
        <button ion-button clear [routerLink]="['/edit-appointment/', booking.$key]">
          <ion-icon name="create" style="zoom:2.0"></ion-icon>
        </button>
        <button ion-button clear (click)="deleteBooking(booking.$key)">
          <ion-icon name="trash" style="zoom:2.0"></ion-icon>
        </button>
      </div>
    </ion-item>
  </ion-list>

Ionic 4 Firebase Angular 8 CRUD

Edit Item in Ionic 4

To edit the item import AppointmentService and then inject into the constructor class. Import the ReactiveFormsModule in edit-appointment.module.ts file.

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

@NgModule({
  imports: [
    ReactiveFormsModule,
    FormsModule,
  ]
})

export class MakeAppointmentPageModule { }

Next, Insert the following code in edit-appointment.page.ts file.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from "@angular/router";
import { FormGroup, FormBuilder } from "@angular/forms";
import { AppointmentService } from './../shared/appointment.service';

@Component({
  selector: 'app-edit-appointment',
  templateUrl: './edit-appointment.page.html',
  styleUrls: ['./edit-appointment.page.scss'],
})

export class EditAppointmentPage implements OnInit {
  updateBookingForm: FormGroup;
  id: any;

  constructor(
    private aptService: AppointmentService,
    private actRoute: ActivatedRoute,
    private router: Router,
    public fb: FormBuilder
  ) {
    this.id = this.actRoute.snapshot.paramMap.get('id');
    this.aptService.getBooking(this.id).valueChanges().subscribe(res => {
      this.updateBookingForm.setValue(res);
    });
  }

  ngOnInit() {
    this.updateBookingForm = this.fb.group({
      name: [''],
      email: [''],
      mobile: ['']
    })
    console.log(this.updateBookingForm.value)
  }

  updateForm() {
    this.aptService.updateBooking(this.id, this.updateBookingForm.value)
      .then(() => {
        this.router.navigate(['/home']);
      })
      .catch(error => console.log(error));
  }
}

To show the edit form, add the following Ionic HTML code in edit-appointment.page.html file.

<ion-header>
  <ion-toolbar>
    <ion-title>
      Edit Appointment
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-list lines="full">
    <form [formGroup]="updateBookingForm" (ngSubmit)="updateForm()">
      <ion-item>
        <ion-label position="floating">Name</ion-label>
        <ion-input formControlName="name" type="text" required></ion-input>
      </ion-item>

      <ion-item>
        <ion-label position="floating">Email</ion-label>
        <ion-input formControlName="email" type="text" required>
        </ion-input>
      </ion-item>

      <ion-item>
        <ion-label position="floating">Mobile</ion-label>
        <ion-input formControlName="mobile" type="text" required>
        </ion-input>
      </ion-item>

      <ion-row>
        <ion-col>
          <ion-button type="submit" color="primary" shape="full" expand="block">Update Appointment</ion-button>
        </ion-col>
      </ion-row>
    </form>
  </ion-list>
</ion-content>

To start the Ionic 4/Angular app, you may try the following 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

Conclusion

We have completed Ionic 4 and Firebase tutorial in which we learned how to create CRUD mobile app with Angular 8. In this tutorial we focused on how to set Firebase in Ionic 4/Angular, how to define CRUD operations in Angular 8 service. Finally, we also checked out how to consume Firebase REST APIs to perform CRUD operation.

Thank for checking out my tutorial, You can get the full code of this tutorial on this GitHub repo.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Thanks for checking this tutorial out :) Let me know if you have any suggestions or issue related to this tutorial, or you want to request a new tutorial. Just shoot me a mail here.