Important Update
The Guide Feature will be discontinued after December 15th, 2023. Until then, you can continue to access and refer to the existing guides.
Author avatar

Jorge Vergara

Using AngularFire2 to Build Ionic 2 and Firebase Apps!

Jorge Vergara

  • Jan 10, 2019
  • 17 Min read
  • Jan 10, 2019
  • 17 Min read
Front-End JavaScript

Ionic 2 + AngularFire2 = Awesomeness!

NOTE: This post was written in 2016, but last updated Nov, 23rd 2017.

In 2016 I/O conference, Google introduced the new version of firebase and all the goodies that came with it; from analytics integration to admob to monetize your apps, it has everything.

As soon as they announced the big update, David East and Jeff Cross started working really hard in making AngularFire2 compatible with the new services.

For ionic framework developers this means we get a really great library that integrates deeply with the framework, facilitating app creation.

I have been using AngularFire2 for over a month now and I find it fascinating how quickly I'm building my apps now.

This guide will help you create an app using Ionic 2 + AngularFire2 so you can make the jump and start building with that combo soon!

Getting Started

We are going to create a small app to keep track of our unpaid bills. This might be a nifty tool if you forget to pay bills sometimes.

The first thing you want to do is to make sure you have the latest version of ionic installed in your machine. Open your terminal and type:

1  npm install -g ionic cordova

This command installs the latest version of the Ionic CLI (you'll use it to create your projects) Cordova (this is how you get that nice installable) and typings to work with TypeScript.

Once you have everything installed, it's time to create your app. Go back to your terminal and navigate to wherever you want to create the app. I create my applications in my development folder. Then create the app.

Next, run the following command:

1$ cd Development
2$ ionic start billTracker blank
3$ cd billTracker

That does a few things:

  • ionic start creates the new app.
  • billTracker is the name we are giving the app.
  • blank tells the CLI we don't want to use any starter template, just a blank project.

Now that you have created a new app and are inside your app folder, it's time to install the dependencies we'll need, right now you'll install firebase and angularfire2.

Go back to your terminal and, inside the billTracker folder, type:

1$ npm install firebase angularfire2

If you are running intro trouble getting this to work you can message me and I'll help you troubleshoot. Easiest way to get in touch is via Twitter @javebratt

Now that we have everything installed, it's time to open your app in your favorite text editor or IDE.

Go to app/app.module.ts and you should see something like this:

1import { BrowserModule } from "@angular/platform-browser";
2import { ErrorHandler, NgModule } from "@angular/core";
3import { IonicApp, IonicErrorHandler, IonicModule } from "ionic-angular";
4import { SplashScreen } from "@ionic-native/splash-screen";
5import { StatusBar } from "@ionic-native/status-bar";
7import { MyApp } from "./app.component";
8import { HomePage } from "../pages/home/home";
11  declarations: [MyApp, HomePage],
12  imports: [BrowserModule, IonicModule.forRoot(MyApp)],
13  bootstrap: [IonicApp],
14  entryComponents: [MyApp, HomePage],
15  providers: [
16    StatusBar,
17    SplashScreen,
18    { provide: ErrorHandler, useClass: IonicErrorHandler }
19  ]
21export class AppModule {}

You need to do a couple of things here. First, at the top of the file, you'll see where we import the components that we need. Go ahead and import AngularFire2:

1import { AngularFireModule } from "angularfire2";
2import { AngularFireDatabaseModule } from "angularfire2/database";

Next, inside the @NgModule initialize your Firebase app:

2  declarations: [...],
3  imports: [
4    BrowserModule,
5    IonicModule.forRoot(MyApp),
6    AngularFireModule.initializeApp({
7      apiKey: "Your Credentials Here",
8      authDomain: "Your Credentials Here",
9      databaseURL: "Your Credentials Here",
10      storageBucket: "Your Credentials Here",
11    }),
12    AngularFireDatabaseModule
13  ],
14  bootstrap: [...],
15  entryComponents: [...],
16  providers: [...]

You'll need to replace the Your credentials here string with your own firebase data.

If you don't know where to get those, you'll need to go to the Firebase Console and click on your app (or create a new one)

You'll see a welcome message like the one in the image below, just pick Add Firebase to your web app and it'll open a pop up with all the info for you to use.


Building the App

Now we are ready to start building because we are already connected to firebase and most of the configuration is done.

The first thing we'll want to do is to add a button, so our users can create new bills inside their app. Go to src0/pages/home/home.html. It should look like this:

2  <ion-navbar>
3    <ion-title>
4      Ionic Blank
5    </ion-title>
6  </ion-navbar>
9<ion-content class="home">

Nothing weird here; it's just the basic html. Change the page title and add a navbar button that sends you to a new page to create bills:

2  <ion-navbar>
3    <ion-title>
4      My Bills
5    </ion-title>
6    <ion-buttons end>
7      <button (click)="newBill()">
8        <ion-icon name="add"></ion-icon>
9      </button>
10    </ion-buttons>
11  </ion-navbar>
14<ion-content class="home">

That will give you a nice + sign to the right of your navbar. Once the user clicks the sign, the newBill() function is called.

Now we need to create newBill() in the home.ts file. To do this, open the file, which will have the following placeholder code:

1import { Component } from '@angular/core';
2import { NavController } from 'ionic-angular';
5  selector: 'page-home',
6  templateUrl: 'home.html'
8export class HomePage {
9  constructor(public navCtrl: NavController) {}

We are going to send the user to a new page to create this bill, so we'll need to use the NavController to send our user there.

First, however, let's create the BillCreate page to see the coolest thing about Ionic: its CLI. You can do a bunch of cool stuff with it, even generate placeholder code. Just open your terminal and type:

ionic g page BillCreate

That little line of code right there creates a bill-create folder, with 4 files in it bill-create.ts bill-create.html bill-create.scss bill-create.module.ts and they all have the boilerplate code already there.

Talk about a productivity boost!

We'll open those files later, for now we just needed to create them to avoid errors when creating the newBill() function.

Go back to home.ts and right after the constructor() create the new function:

2  this.navCtrl.push('BillCreatePage');

This will just take our user to the newly created page where we'll add the form to create a new bill.

So go to pages/bill-create/bill-create.html and delete everything in there, we'll replace it with this:

2  <ion-navbar>
3    <ion-title>New Bill</ion-title>
4  </ion-navbar>
7<ion-content padding class="bill-create">
8  <ion-item>
9    <ion-label stacked>Bill Name</ion-label>
10    <ion-input [(ngModel)]="name" type="text" placeholder="How do you identify this bill?"></ion-input>
11  </ion-item>
13  <ion-item>
14    <ion-label stacked>Amount</ion-label>
15    <ion-input [(ngModel)]="amount" type="number" placeholder="How much will you have to pay?"></ion-input>
16  </ion-item>
18  <ion-item>
19    <ion-label>Due Date</ion-label>
20    <ion-datetime displayFormat="D MMM, YY" pickerFormat="DD MMM YYYY" [(ngModel)]="dueDate"></ion-datetime>
21  </ion-item>
23  <button block (click)="createBill(name, amount, dueDate)">
24    Create Bill
25  </button>

The first two items created are just regular inputs; you can see everything about them in the ionic docs. We are just adding an [(ngModel)] to them to hold the values.

The third item is a date-time item, this is why Ionic is so awesome, you add that input and it will add a beautifully designed date picker to your app.

And finally we add a button that calls the createBill() method passing the values of the inputs.

Now we need to go to bill-create.ts and create that function. Open the file and you'll see this:

1import { Component } from '@angular/core';
2import { IonicPage, NavController } from 'ionic-angular';
6  selector: 'page-bill-create',
7  templateUrl: 'bill-create.html'
9export class BillCreatePage {
10  constructor(public navCtrl: NavController) {}

We'll need to import AngularFire and our list observable to this file, so right below your last import statement type:

import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';

  • AngularFireDatabase gives us the AngularFire2 magic, where we can call lists, objects, auth methods, etc.
  • AngularFireList gives us the observable we'll be using, it will subscribe to the list and sync it in real time with our app.

Right before the constructor, create a variable that will hold our list. If you are getting confused on where to do this don't worry, I'll show you the completed file later.

billList: AngularFireList<any>;

Inject AngularFireDatabase into your constructor.

2  public navCtrl: NavController,
3  public afDatabase: AngularFireDatabase
4) {}

Now create a binding to the list inside the constructor:

this.billList = afDatabase.list('/bills');

This will keep billList synced with our Firebase real-time database on the /bills node.

To add new bills to that list, we just need to use angularfire's push() method:

1createBill(name, amount, dueDate) {
2  const newBillRef = this.billList.push({});
4  newBillRef.set({
5    name: name,
6    amount: amount,
7    dueDate: dueDate,
8    paid: false,
9    id: newBillRef.key
10  }).then( newBill => {
11    this.navCtrl.pop();
12  }, error => {
13    console.log(error);
14  });
  • this.billList.push() is adding a new bill to the list, passing the values that the method is receiving, and setting the paid property to false.
  • The .then() function happens after the bill is added to the list and it does 2 things:
    • First it goes back one page (to the Home Page) after creating the bill.
    • Second, if any error occurs on the process it's going to log it to the console.

The final version of the file should look like this:

1import { Component } from '@angular/core';
2import { IonicPage, NavController } from 'ionic-angular';
3import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
7  selector: 'page-bill-create',
8  templateUrl: 'bill-create.html'
10export class BillCreatePage {
11  billList: AngularFireList<any>;
12  constructor(
13    public navCtrl: NavController,
14    public afDatabase: AngularFireDatabase
15  ) {
16    this.billList = afDatabase.list('/bills');
17  }
19  createBill(name, amount, dueDate) {
20    const newBillRef = this.billList.push({});
22    newBillRef.set({
23      name: name,
24      amount: amount,
25      dueDate: dueDate,
26      paid: false,
27      id: newBillRef.key
28    }).then( newBill => {
29      this.navCtrl.pop();
30    }, error => {
31      console.log(error);
32    });
33  }


Great! We can create bills now. Is that it for this app?

Nope, now we are going to list those bills in the Home page. To do this, open home.ts, import AngularFireDatabase, inject it to the controller, and bind it to a list:

1import { Component } from '@angular/core';
2import { NavController } from 'ionic-angular';
3import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
6  templateUrl: 'home.html',
8export class HomePage {
10  billList: AngularFireList<any>;
11  constructor(
12    public navCtrl: NavController,
13    public afDatabase: AngularFireDatabase
14  ) {
15    this.billList = afDatabase.list('/bills').valueChanges();
16  }
18  newBill(){
19    this.navCtrl.push('BillCreatePage');
20  }

We're going to go to home.html and create a couple of cards to show both paid and unpaid bills. However, since I want to format the Due Date, I'm going to need a little help.

You see, Angular2 pipes (that's what we use to format dates) break when we are using Ionic to build mobile apps. We're going to use a custom pipe from angular2-moment instead.

Open your terminal and type:

1npm install --save angular2-moment

This will install both the module and its typings, you can read the docs here but we'll only use a small part of it.

Import the pipe we'll need:

import { DateFormatPipe } from 'angular2-moment';

Now inside our @Component declaration we need to express we'll use that pipe:

2  templateUrl: 'build/pages/home/home.html',
3  selector: 'app',
4  pipes: [DateFormatPipe]

And that's it! Go to the home.html file to use our app. Just open the file and, inside the ion-content, create a card to hold our unpaid bills:

2  <ion-card-header>
3    Pending Bills
4  </ion-card-header>
6  <ion-list>
7    <ion-item text-wrap *ngFor="let bill of billList | async" (click)="promptPayment("
8      [class.hide]="bill.paid == true">
9      <ion-icon name="timer" danger item-left></ion-icon>
10      <h2>{{}}</h2>
11      <h3>Total: <strong>${{bill.amount}}</strong></h3>
12      <p>Pay before: <strong>{{bill.dueDate | amDateFormat: 'LL'}}</strong></p>
13    </ion-item>
14  </ion-list>

There are a few things going on here:

  • *ngFor="let bill of billList | async" tells our item to repeat for every bill it finds on our billList.
  • (click)="promptPayment( tells our system to call that function when users tap on the item. (we'll create that function in a minute).
  • [class.hide]="bill.paid == true" says that if the bill is already paid, add the hide css class, which will hide the item from the list.

And after that we are creating a regular item and binding the bill properties to it.

See this line <p>Pay before: <strong>{{bill.dueDate | amDateFormat: 'LL'}}</strong></p> this is where we are using angular2-moment to format the date.

Right after that card we'll create another card, this time to hold the list of the bills our user already paid:

2  <ion-card-header>
3    Paid Bills
4  </ion-card-header>
6  <ion-list>
7    <ion-item text-wrap *ngFor="let bill of billList | async"
8      [class.hide]="bill.paid == false">
9      <ion-icon name="checkmark-circle" favorite item-left></ion-icon>
10      <h2>{{}}</h2>
11      <h3>Total: <strong>${{bill.amount}}</strong></h3>
12    </ion-item>
13  </ion-list>

It's almost the same as before, we are just adding the hide class to the ones that haven't been paid yet.


Remember when we said we'd create the promptPayment() function in a minute? It's that time now. Go to home.ts and import AlertController; we'll need this to create a prompt:

import { NavController, AlertController } from 'ionic-angular';

Now we just need to create the function:

1promptPayment(billId: string) {
2  let alert = this.alertCtrl.create({
3    message: "Mark as paid?",
4    buttons: [
5      {
6        text: 'Cancel',
7      },
8      {
9        text: 'Mark as Paid',
10        handler: data => {
11          this.billList.update(billId, { paid: true });
12        }
13      }
14    ]
15  });
16  alert.present();

The code is really easy to follow. We are creating a prompt that's going to ask the user: Mark as paid? and our user is going to get 2 buttons:

  • Cancel, which does nothing.
  • Mark as Paid, which will call this.billList.update(billId, { paid: true });. This method will take the billId we're sending from the html and update that bill with AngularFire's update() method.

Piece of cake!

Take Your Skills to the Next Step

The entire source code for this app is available on github.

If you want to take your Ionic + Firebase skills to the next step, I created a free course that will help you build your first Firebase powered mobile app. All you have to do is go here.