Angular + Firebase: Step by step guide

Before starting with this guide, I just want to clarify what are Angular and Firebase, in case someone reading this is not yet familiar with these powerful tools.

  • Angular: A component-based framework for building scalable web applications.
  • Firebase: A development platform that helps you build, improve, and grow your applications.

These tools are part of Google’s development stack, and are very powerful, today we’re going to develop a web application using Angular and Firestore, the database service provided by Firebase.

What are we going to build?

Well, for this guide we’re going to build an application to save sandwich reviews, so we will never forget again where we can get the best sandwiches in town.

 We’re going to do this in 5 steps:

  1. Create an Angular application
  2. Create a Firebase project
  3. Connect projects
  4. Write on Firestore
  5. Read from Firestore

Let’s get started creating our Angular application!

1. Create the Angular application

1.1 Setup environment

The only prerequisites for using the Angular framework are:

  • Node.js — for more information on installing Node.js, see https://nodejs.org/.
  • npm package manager — in this guide we’re using npm client, which is already installed on Node.js by default.

1.2 Install the Angular CLI

We’re going to be using the Angular CLI, to install it just open a terminal window and run the following command:

npm install -g @angular/cli

1.2 Create an Angular App

To create a new Angular app we’re going to use the ng new command to create an app with the name sandwich-review. For this time just accept the default configurations by pressing Enter, and then navigate inside the project’s folder.

ng new sandwich-review
cd sandwich-review

1.3 Add Bootstrap

To give our Sandwich Review app a good-looking UI in an easy way, we’re going to install bootstrap via npm.To install it, run the following command inside the project’s folder on the terminal:

npm install bootstrap

Now add bootstrap to the angular.json file inside the styles array:

“styles”: [
  “src/styles.scss”,
  “node_modules/bootstrap/dist/css/bootstrap.min.css”
],

Now bootstrap is installed and we have imported its styles to be used later inside our application.

1.4 Run the application

Now we’re going to navigate to the app’s folder we just created and run the application locally on our machine.

ng serve –open

This is going to serve our application locally, and open our browser in the address https://stackcodify.com:4200/. We’re going to see all the changes made to our application here.

Ok, so far we have created an Angular app, we installed bootstrap, and we have it running on our local machine, now we’re going to proceed to create the Firebase project.

2. Add a Firebase project

1.1 Create project

Sign in to the Firebase Console using a Google account: https://console.firebase.google.com/ and then click on Create a project.

Enter the name of your project, and accept Firebase terms and conditions.

1.2 Register your app

 Now that we created our project, we’re going to register our angular application in this project by pressing the web icon (</>)

Now we pick a nickname for the application, in this case, I’m going to name it sandwich-review-webapp. Now click on Register app.

We’re going to skip the next steps because we’re not going to use those services during this guide, so just click on Continue until the configuration is finished.

1.3 Create database

Now we’re going to create a new database by going to the Firestore Database tab on the side menu and then clicking on Create database.

We are not going to configure security rules for now, so just select Start in test mode, and then pick the default Firestore location.

Now we have a Firebase project created and the Firestore database is enabled, now we’re going to integrate our Angular application with our Firebase project for them to work together.

3. Connect Projects

3.1 Install firebase in our Angular application

Now we are going to install the firebase package via npm running the following command on the terminal (inside the folder of our angular application):

npm install –save firebase

3.2 Add the firebase configuration

Now we’re going to link our firebase project with our Angular application. In order to do that we need the firebaseConfig object which can be found in the Project Settings inside our Firebase Console. Let’s copy that configuration object.

In our Angular app, we’re going to (1) import the firebase package we installed, and (2) add the configuration object we copied to our src/app/app.component.ts file, to initialize the app. Your file should look like the following:

 import { Component, OnInit } from ‘@angular/core’;
import firebase from ‘firebase/app’; // (1)
 @Component({
  selector: ‘app-root’,
  templateUrl: ‘./app.component.html’,
  styleUrls: [‘./app.component.scss’],
})
 export class AppComponent implements OnInit {
 ngOnInit() {
    const firebaseConfig = { // (2)
      apiKey: ‘YOUR-API-KEY’,
      authDomain: ‘YOUR-AUTH-DOMAIN’,
      projectId: ‘YOUR-PROJECT-ID’,
      storageBucket: ‘YOUR-STORAGE-BUCKET’,
      messagingSenderId: ‘YOUR-MESSAGING-SENDER-IR’,
      appId: ‘YOUR-APP-ID’,
      measurementId: ‘YOUR-MEASUREMENT-ID’,
    };
    firebase.initializeApp(firebaseConfig);
  }
} 

Now that our Angular app and our Firebase project are connected, on the next step we’re going to start using the Firestore database to write/read data from the Firebase.

4. Write on Firestore

First of all, we are going to replace the content of our src/app/component.html file with the following code, which defines a form with two inputs for the variables name and score, and a button that calls the function addSandwich. Note that we’re using bootstrap CSS classes here, so we don’t need to style this.

<div class=”container p-4">
  <div class=”card mb-4” style=”width: 30rem”>
    <div class=”card-body”>
      <h5 class=”card-title mb-4">New Sandwich</h5>
      <form>
        <div class=”form-group mb-2">
          <label for=”name”>Name</label>
          <input id=”name”
                 name=”name”                 
                 type=”text”
                 class=”form-control”
                 [(ngModel)]=”name”/>
        </div>       
        <div class=”form-group mb-2">
          <label for=”name”>Score</label>
          <input id=”score”
                 name=”score”
                 type=”number”
                 class=”form-control”
                 [(ngModel)]=”score”/>
        </div>
        <button class=”btn btn-primary” type=”submit”
                (click)="addSandwich()">Add</button>
      </form>
    </div>
  </div>
</div>

Our interface should look like this on the browser:

Now we’re going to edit the src/app/app.component.ts to (1) add firestore to the imports, (2) create the name and score properties, and (3) create the addSandwich function that is going to create a new object in our database. In the end, our file should look like this:

 import { Component, OnInit } from ‘@angular/core’;
import firebase from ‘firebase/app’;
import 'firebase/firestore'; // (1)
 @Component({
  selector: ‘app-root’,
  templateUrl: ‘./app.component.html’,
  styleUrls: [‘./app.component.scss’],
})
 export class AppComponent implements OnInit {
  name = ''; // (2)
  score = 0;
 ngOnInit() {
    const firebaseConfig = {
      apiKey: ‘YOUR-API-KEY’,
      authDomain: ‘YOUR-AUTH-DOMAIN’,
      projectId: ‘YOUR-PROJECT-ID’,
      storageBucket: ‘YOUR-STORAGE-BUCKET’,
      messagingSenderId: ‘YOUR-MESSAGING-SENDER-IR’,
      appId: ‘YOUR-APP-ID’,
      measurementId: ‘YOUR-MEASUREMENT-ID’,
    };
    firebase.initializeApp(firebaseConfig);
  }
 async addSandwich() { // (3)
    await firebase.firestore().collection('sandwiches').add({
      name: this.name,
      score: this.score,
    });
  }
} 

To add a Sandwich to our database, we have to enter the data on the form in the user interface and click the Add button. This is going to call the addSandwich function that is going to create an object with the name and score properties in the sandwiches collection.

You can check the database in the Firebase Console, inside the Firestore tab. Note that Firestore automatically generated an id for this object.

We already learned how to write data in our firestore database from our Angular application, now we’re going to see how to retrieve data and display it on our application.

5. Read from Firestore

First of all, we are going to add the following code to the src/app/component.html file to display a list with the sandwiches on our database.

 <div class=”container p-4">
  <div class=”card mb-4” style=”width: 30rem”>
    <div class=”card-body”>
      <h5 class=”card-title mb-4">New Sandwich</h5>
      <form>
        <div class=”form-group mb-2">
          <label for=”name”>Name</label>
          <input id=”name”
                 name=”name”                 
                 type=”text”
                 class=”form-control”
                 [(ngModel)]=”name”/>
        </div>       
        <div class=”form-group mb-2">
          <label for=”name”>Score</label>
          <input id=”score”
                 name=”score”
                 type=”number”
                 class=”form-control”
                 [(ngModel)]=”score”/>
        </div>
        <button class=”btn btn-primary” type=”submit”
                (click)="addSandwich()">Add</button>
      </form>
    </div>
  </div>
</div>
 <div class=”card mb-4" style=”width: 30rem”>
  <div class=”card-body”>
    <h5 class=”card-title mb-4”>All sandwiches</h5>
    <ul>
      <li *ngFor=”let sandwich of sandwiches”>
        <h6>
          {{ sandwich.name }}
          <span class=”badge bg-success”>
            {{ sandwich.score }}/10
          </span>
        </h6>
      </li>
    </ul>
  </div>
</div> 

Now we are going to (1) create a sandwiches array, to store the data we’re going to download, and then we’re going to create (2) the getSandwiches function to download the data from firestore.

 import { Component, OnInit } from ‘@angular/core’;
import firebase from ‘firebase/app’;
import 'firebase/firestore';
 @Component({
  selector: ‘app-root’,
  templateUrl: ‘./app.component.html’,
  styleUrls: [‘./app.component.scss’],
})
 export class AppComponent implements OnInit {
  name = '';
  score = 0;
  sandwiches = []; // (1)
 ngOnInit() {
    const firebaseConfig = {
      apiKey: ‘YOUR-API-KEY’,
      authDomain: ‘YOUR-AUTH-DOMAIN’,
      projectId: ‘YOUR-PROJECT-ID’,
      storageBucket: ‘YOUR-STORAGE-BUCKET’,
      messagingSenderId: ‘YOUR-MESSAGING-SENDER-IR’,
      appId: ‘YOUR-APP-ID’,
      measurementId: ‘YOUR-MEASUREMENT-ID’,
    };
    firebase.initializeApp(firebaseConfig);
     this.getSandwiches(); // (2)
   }
   async addSandwich() {
    await firebase.firestore().collection('sandwiches').add({
      name: this.name,
      score: this.score,
    });
    this.getSandwiches(); // (2) 
}
   async getSandwiches() { // (2)
    const snapshot = await firebase.firestore().collection('sandwiches').get();
    snapshot.forEach((doc) => this.sandwiches.push(doc.data()));
  }
 } 

Now, if you refresh the page, you should be able to see all the sandwiches that have been stored on our database on the second card.

We already learned how to read data from our firestore database on our Angular application and how to display it on the screen.

This was an introductory guide on the development of web applications using Angular and Firebase. We learned how to create a new Angular Application, a Firebase Project, and how to use Firestore to read/write data into our database.

I hope you enjoyed this step-by-step guide, please feel free to contact me if you have any questions or doubts regarding this topic.

Reference:
– Angular docs:https://angular.io/docs
Firebase docs: https://firebase.google.com/docs
Firestore docs: https://firebase.google.com/docs/firestore

Fran Sandi
Full stack developer with 6+ years of experience I'm a Software Engineer passionate about Technology and its potential to make things better. I have been working in agile teams as a JavaScript developer for the last 6 years, using tools like Angular, Node.js, Firebase, and Ionic.

Related Articles

Leave A Reply

Please enter your comment!
Please enter your name here

Stay on Top - Get the daily news in your inbox