At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

,

Creating a Web App From Scratch Using Angular 5 and Firebase

  • By Manikandan Thangaraj
  • May 18, 2018
  • 2249 Views

Want to create a web app from scratch using Angular 5? Don’t know where to start?
Well, this article helps you with basic of creating a web app and the process of adding Firebase library for handling real-time data.
First, will start with creating an angular web app and Angular Command-line interface then will move to integration part of Firebase with an Angular web app.
Before stepping ahead, let’s have a quick look at what is Angular and Firebase.

Introducing Angular Framework

Angular is a platform that makes it easy to build applications with the web. It combines declarative templates, dependency injection, an end to end tooling, and integrated best practices to solve development challenges. Angular empowers developers to build applications that live on the web, mobile, or the desktop.

Introducing Firebase

Firebase is a cloud-based database and a backend service with schema-less data system which provides a real-time data handling. It provides a powerful Android, iOS, and JavaScript SDKs and API to develop high-end mobile and web applications. Firebase, Inc in 2011 develop firebase and acquired by Google in 2014.
It provides 3 core services
Real-time Database − Firebase will support JSON data so the users who were connected to it will receive the live updates after every change that occurs.
Authentication − We can use anonymous, password or different social authentications.
Hosting − Applications can be deployed with a secure connection to Firebase servers.

Introducing Project Use-Case

Here we are going to create fresh Angular Application with sample add/edit process with Firebase.

Quote - Banner-Blog

Following tools and modules are used for this project:

– Angular CLI
– Angular 5
– Firebase project
– Firebase and angularfire2 (npm packages)
Let’s get into the business.

Setting up the Angular Application:

Step 1: Set up the Development Environment
Install Node.js and npm.
Then install the Angular CLI globally.

npm install -g @angular/cli

 
Step 2: Create new Angular Project and Install required packages.

ng new angularfire-app
cd angularfire-app

 
Step 3: Run your application.

ng serve --open

 
Now the web application will get open in a browser.

welcome to app

Setting Up Firebase Cloud Database:

Basically, Firebase is the cloud database, so need to configure online. Google provides a Firebase console for managing Firebase.
Two steps are required to configure,

Create a Firebase project

To create a new Firebase project go to the https://firebase.google.com and create a fresh google account or sign in to your already existing account. After successfully logged in successfully click on the link Go To Console to access the Firebase back-end:

Here you can click on add project or existing projects. You will be taken to the project console next:

Click on the link “Add Firebase to your web app” to access the following dialog:

Here you can find the JavaScript code which is needed to initialize the Firebase project for your website. However, we are going to use only some part of the code.

Integrate/Connect Firebase with Angular

In the last screen, you can see the config object with some key-pair values. Just copy the config object and insert into the environments/environment.ts config:

{
production: false,
firebase: {
apiKey: "[...]",
authDomain: "[...]",
databaseURL: "[...]",
projectId: "[...]",
storageBucket: "[...]",
messagingSenderId: "[...]"
}
}

 
The key-value pairs are inserted into a new property named as firebase. The same needs to be inserted into environments/environment.prod.ts for production server:

{
production: true,
firebase: {
apiKey: "[...]",
authDomain: "[...]",
databaseURL: "[...]",
projectId: "[...]",
storageBucket: "[...]",
messagingSenderId: "[...]"
}
}

 
That’s needed to make the Firebase settings available for both development or production.

Adding Libraries:

To work with Firebase in Angular, we need some packages to handle. Firebase is providing Node Package handle APIs. Moreover, angular provide official library called “angularfire2”. We need both packages.
[code lang=”nginx”]npm install –save firebase angularfire2[/code]
Above command will download and install the node packages to node_modules and will add the dependencies to the package.json file.
Insert the following import statements into app.module.ts:

import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';

 
Also add the modules AngularFireModule, AngularFireDatabaseModule, and AngularFireAuthModule to the imports array of the @NgModule decorator in the following way:

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireDatabaseModule,
AngularFireAuthModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

 

Retrieving Data From Firebase

Finally, we are into Retrieving/Adding/Update and delete real-time data to Firebase. Like all other NoSQL, firebases also maintaining data in JSON format. Let’s assume that following JSON data structure has already been created:

{
"messages": {
"1": {
"text": "Hello",
"created": "13/05/2018, 13:18:37",
"modified": "13/05/2018, 13:18:37"
},
"2": {
"text": "How are you?",
"created": "13/05/2018, 13:18:37",
"modified": "13/05/2018, 13:18:37"
},
"3": {
"text": "Fine",
"created": "13/05/2018, 13:18:37",
"modified": "13/05/2018, 13:18:37"
}
}
}

 
Every table has “list” in Firebase and firebase provide Javascript Features to manage the lists. For example, let creates an Angular component to create, update and retrieve data from Firebase list. We can generate a component using AngularCli with below command:
[code lang=”nginx”]ng g component messages[/code]
It will create a Message folder inside app/src. And, inside the Message folder, we can see component support files.
Now, Edit the messages.component.js and replace with below code.

import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'messages',
templateUrl: './messages.component.html',
styleUrls: ['./messages.component.css']
})
export class MessagesComponent implements OnInit {
itemsRef: AngularFireList<any>;
items: Observable<any[]>;
projectsObservable: Observable<any[]>;
constructor(private db: AngularFireDatabase) { }
ngOnInit() {
this.itemsRef = this.db.list('messages');
// Use snapshotChanges().map() to store the key
this.items = this.itemsRef.snapshotChanges().map(changes => {
return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
}
addItem(newName: string) {
this.itemsRef.push({ text: newName,created:(new Date()).toLocaleString(),modified:(new Date()).toLocaleString() });
}
updateItem(key: string, newText: string) {
this.itemsRef.update(key, { text: newText,modified:(new Date()).toLocaleString()});
}
deleteItem(key: string) {
this.itemsRef.remove(key);
}
deleteEverything() {
this.itemsRef.remove();
}
}

 
Here you can see AngularFireDatabase and AngularFireList service injecting into the component. AngularFireDatabase service will connect the Firebase and AngularFireList used to handle “List” in the Firebase database. The line “this.itemsRef = this.db.list(‘messages’)” create an object and gain access to the existing messages or create and gain access to messages list.
We can use both valueChanges and snapshotChanges method to retrieve data, but here we used snapshotChanges to get data as an object to get key. “push” method will insert data to list, “update” method will update record from the list and “remove” method remove the record.
The “items” Observable member will have data. We can access this “items” member in template messages.component.html:

<input type="text" placeholder="message" #newitem />
<button (click)="addItem(newitem.value)">Add</button>
<button (click)="deleteEverything()">Delete All</button>
<br><br>
<table class="table">
<tbody>
<tr *ngFor="let item of items | async">
<td><input type="text" #updatetext [value]="item.text" /></td>
<td>{{item.created}}</td>
<td>{{item.modified}}</td>
<td><button (click)="updateItem(item.key, updatetext.value)">Update</button>
<button (click)="deleteItem(item.key)">Delete</button></td>
</tr>
</tbody>
</table>

 
Finally, you need to include the <messages> element in the template code in app.component.ts:

<!--The content below is only a placeholder and can be replaced.-->
<div class="container">
<div class="starter-template">
<h1>Angular, Bootstrap & Firebase Starter Application</h1>
<p class="lead">This application is built with Angular 5, Bootstrap 4 and Firebase</p>
<h3>Projects List</h3>
<messages></messages>
</div>
</div>

 
Now the result we will look like this:

[ Related: How To Deploy Your Web Application To Firebase Hosting ]

Successfully we have built the web Application with Angular 5, Bootstrap 4 and Firebase application from scratch and learned required libraries, the project set up. Finally, integrated everything together. Hope this will help you to understand the basics of firebase and their uses. What are you waiting for? Try now and share your awesome result with us.
You can get the complete Source code here and for more info reach us at info@agiratech.com
Happy Coding…
If you are looking for angular developers for your project ? Hire Angular developer from Agira Technologies to build best web-apps at affordable rates. Our dedicated Angular developers are well-versed with all the updates and ensure top-notch web applications development to meet your business requirements. For any queries reach us via info@agiratech.com

Manikandan Thangaraj

A Passionate full stack developer with 9 years of experience in full stack web application development and expertise in technologies like PHP and Angular. He has huge craze in learning new things about technologies and constantly shares his knowledge with others.