Using angularfire2 build Angular and Firebase Application & also deploy Angular Application to Firebase Hosting

Angularfire2 = Awesome SPA(single page application) at your fingertips using Angular and Firebase.

Angularfire2 is really a great library to work with angular and firebase. This library will fascinating us to develop an Angular application in just no time. So in this tutorial I am going to show you how you can build the application using firebase and angular. And at the end I will show you how you can host your application to firebase. In short in this tutorial I am going to show how you can create the application from scratch to deployment. Are guys ready to dive with me?? Yeah so let’s get started..


We are going to build a simple application in which I will cover following operations.

  • Display All Product


Setting up Firebase

Then from console click on create new project

Go to Authentication tab and then click on web setup right side top corner to get configuration

Then click on web setup (top right corner),to get your configuration

Then click on Database button to set rules for database and navigate to rules tab and write as shown below

Now navigate back to data tab and create a child under the root node which is name of your project.

Now click on storage tab to enable storage of images, and create one folder as shown below

After creating directory inside storage , also don’t forget to set its rules, by navigating to rules tab

So far we had created a firebase project which enables the authentication using email and password and created a database which is given both read and write permissions and also enable storage to store the photos of uploaded products. So now we are ready to dive .

Angular side:

· Angular CLI should > 1.0.6 (latest is most preferable)

o If you don’t know how to upgrade your current cli just follow the following steps

§ npm uninstall –g @angular/cli (it will remove current Angular Cli)

§ npm cache clean ( It will clean the cache)

§ npm install –g @angular/cli@latest (it will install the latest cli)

o If you don’t know how to install Angular Cli or you are new to Angular Cli , Please Follow my blog here for stp by step guide of how to install angular Cli.

· Now if you done with Angular Cli ,we will create the new application

o ng new firebasecrudDemo (it will create new angular application)

· Then navigate to the directory in which we had created the firebasecrudDemo project. Inside the firebasecrudDemo directory write following command in your command prompt or power shell,

npm install firebase angularfire2 — -save (it will install angularfire2 library )

Setting app.modult.ts

Now first of all we need to set the web configuration (remember which I had copied from firebase!) as shown below

export const firebaseconfig={apiKey: "",authDomain: "",databaseURL: "",projectId: "",storageBucket: "",messagingSenderId: ""}

And add it in Imports array of app.module.ts file

imports: [BrowserModule,FormsModule,HttpModule,    AngularFireModule.initializeApp(firebaseconfig)]

Also imports following package to provide two services

  1. angularfireauth (which is required for user authentication and creation)
import { AngularFireModule } from "angularfire2";import { AngularFireDatabase } from "angularfire2/database";providers: [AngularFireDatabase]

So final app.module.ts will look like following,

Add new Products to Database:

As we had created empty database first we need to insert a record to database. As we are using firebase database which is nosql database, so we don’t need to create table and columns and everything. We just need to create a root ,which we had created in previous steps and named that root to products.

Will divide this process in following steps:

  • Design for add new product
<div class="row"><div class="container"><h2>Add Product</h2><div class="form-group"><input type="text" placeholder="Enter name of the Product" class="form-control" #field ></div><div class="form-group"><input type="number" placeholder="Enter price" class="form-control" #price ></div><div class="form-group"><input  class="form-control"  (change)="upload(f,img)"  type="file" #f/></div><div class="form-group"><img height="100" width="100" alt="Preview Will be displayed here"  src=""  #img></div><button (click)="add(field,img,price)" class="btn btn-primary">Add Product</button></div></div>


import { AngularFireDatabase, FirebaseListObservable } from "angularfire2/database";import 'firebase/storage'import * as firebase from 'firebase';constructor(public _database: AngularFireDatabase) {}

Angularfiredatabase is required for making connection with database and it will also provide us various methods for add, update, delete and display products.

Firebaselistobservable is used to store data which is retrieved from database.

Firebase/Storage is used to upload the images or files to firebase storage.

Create the array of type firebaselistobservable and uploadtask

arr: FirebaseListObservable<any[]>;public uploadTask:;

Upload method (for uploading file to firebase storage)

upload(f, img) {let storageReference ='/images/' + f.files[0].name);this.uploadTask = storageReference.put(f.files[0]);this.uploadTask.on('state_changed', function (snapshot) {// Handle Progress of fileupload}, function (error) {// Handle unsuccessful uploads}, function () {// Handle successful uploads on complete// For instance, get the download URL: (url) {// Insert url into an <img> tag to "download"img.src = url;});});}

Here upload method has two arguments, f is a reference of input control which we had put on our html page and same img is reference of our img control.

  • Add method
add(field,img,price) {this.arr.push({ pname: field.value, createdAt: new Date().toString(),price:price.value, likes: 0,image:img.src});}

so here in Add method I am using push method of array , inside the push method I am creating the object which I need to store to database. So now our root products has following nodes pname,createdAt,price,likes and image. Remember firebase is nosql database so it will store the data as tree structure.

The parameters field,img and price are the references of their corresponding html elements.

Display Products

Now as we are done with adding new product , it’s time to fetch the records from the database.

Html for products display

<div class="row"><hr><div class="container"><h2>Products</h2><div class="row"><div class="col-md-4 zweet-card" *ngFor="let item of arr | async"><div class="panel panel-default"><div class="panel-body"><strong>{{item.pname}}</strong>{{item.price | currency:'INR':true }}<small>{{item.createdAt| date: 'd/M/y H.m a'}}</small><img height="100" width="100" src="{{item.image}}"><div class="btn btn-danger btn-sm btn-remove"  (click)="remove(item.$key)"><i class="glyphicon glyphicon-remove"></i></div><div class="btn btn-info btn-sm pull-right btn-like" (click)="like(item.$key,item.likes)"><div class="badge badge-like-count">{{item.likes}}</div><i class="glyphicon glyphicon-thumbs-up"></i></div></div></div></div></div></div></div>

Code for products display

arr: FirebaseListObservable<any[]>;ngOnInit() {this.arr = this._database.list('/products');}

Which will fetch all the records from the database with root named as products and binds all the records to html asynchronously using that async pipe.

Delete Product

remove($key) {this.arr.remove($key);}

In Firebase when we add new record to database it will automatically generates the unique key or token ,which will be used to fetch the particular record uniquely . So I am using that key value to remove the particular record from database.

Update Likes for Products

like($key, like) {this.arr.update($key, { likes: like + 1 });}

This will update total like count on particular product. So here I am passing two arguments, first is that unique key and second is like to update.

Final Source Code



Isn’t it easy guys? Now it is time to do even more easiest thing!!! Right !! Now we will see how to host angular application on firebase hosting. Exited guys? Yeah so let’s dive in to it.

Deploy Angular Application on Firebase Hosting

We had already created project on firebase using console, so now we only required to install firebase cli. To do so navigate to your project directory in command prompt and write the following code.

cmd> npm install –g firebase-tools

cmd> firebase login

cmd> firebase init

It will ask you few questions like what features of firebase cli you want to use? In our case select hosting only using space.

Second question it will ask for project directory → then select the directory of your project which you have created using firebase console.

What do you want to use as your public directory? In our case name of the public directory should be dist (which we are going to create shortly).

Configure as a single page application? Yes

Done Initiation is completed.

Now it is time to create build of your project which is just created.

To generate build using angular cli navigate to your project directory in command prompt and write following code.

cmd> ng build — -prod — — aot

it will generate a build using ahead of time compilation.

Now final step is

cmd> firebase deploy


We covered a lot in this tutorial. Setting up the firebase project, Creating angular project, Add new product , Display product ,Delete product ,Deployed angular application on firebase hosting and many more. I hope it will be helpful to you.

You can download the source code from here.

Jinal Shah is corporate trainer on different technology like node.Js, Angular,Ionic 2, BOT Framework etc.