Angular 7 CRUD with Firebase & Firestore

In this tutorial, you'll be using Angular 7 with Firebase and Firestore to create a project that implements the common CRUD operations.

CRUD stands for Create, Read, Update and Delete that refer to the operations that most apps need to make against a database. In this example, the database is Firestore database that exists on the cloud.

Prerequisites

Before starting this tutorial, you first need to make sure, you have:

  • A recent version of Node.js (v8.9+) and NPM installed on your system,
  • The latest Angular CLI 7 installed on your system.

If you the prerequisites, then you are ready to start your project.

Creating an Angular 7 Project

The first step in this tutorial is creating a new Angular project using the CLI. Head over to your terminal and run the following command:

$ ng new angular7-crud-firestore

The CLI will ask if you want to add routing to your project (you can choose any option you want) and which style sheet format you want to use (You can select CSS).

After that, your project files will be generated and your project's dependencies will be installed.

Creating a Firebase Project and Firestore Database

Now that your project is generated, you need to proceed by creating a Firebase project and a Firestore database. For this matter, you simply need to go to Firebase Console and create a new Firebase project.

Next head to the Project Overview >Develop >Database page and create new Firestore database . For now, make sure you enable test mode so you don't need any permissions to access the database.

Installing and Adding Firebase to your Angular Project.

After creating your Firebase project and your Firestore database you next need to install the firebase and @angular/firebase packages:

$ npm install --save firebase @angular/firebase

Next go to your Firebase project overview then click on web and copy the config data.

Next, open the environments/environment.ts file in your Angular project and add the firebaseConfig object inside the environment object.

export const environment = {
  production: false,
  firebaseConfig : {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    databaseURL: "YOUR_DATABASE_URL",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID"
  }
};

Finallyn, you have to setup Firebase in your project. Open the src/app/app.module.ts file and update it accordingly:

import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { environment } from '../environments/environment';

@NgModule({
        // [...]
    imports: [
        // [...]
        AngularFireModule.initializeApp(environment.firebaseConfig),
        AngularFireDatabaseModule
    ],

You simply import AngularFireModule and AngularFireDatabaseModule you add them to the imports array of the main application module.

You also call the .initializeApp method of AngularFireModule to pass the configuration object that you added earlier to environments/environment.ts file.

That's it, you now have added Firebase and Firestore to your Angular 7 project.

Create an Angular 7 Model

After setting up Firestore in your project, you can proceed by creating a model class. In the simple example, we suppose that you are creating an insurance app where we need to manage a set of policies.

An insurance application will often contain more that one type of data like clients, employees and policies etc. In this example, we'll just focus on the policy entity:

Let's create a model for our insurance policy entity:

$ ng g model policy

Open the src/policy.model.ts file and update it accordingly:

export class Policy {
    id: string;
    policyNumber: string;
    creationDate: Date;
    effectiveDate: Date;
    expireDate: Date;
    paymentOption: string;
    policyAmount: number;
    extraInfo: string;
}

This is an example of an insurance policy with many fields and relationships with other entities omitted for the sake of simplicity.

Creating an Angular 7 Service

An Angular service allows you to encapsulate the code that could be repeated in many places in your project. Using the Angular CLI, run the following command to generate a service:

$ ng g service policy

Open the src/policy.service.ts file and update it accordingly. First, import AngularFirestore at the top of the file:

import { AngularFirestore } from '@angular/fire/firestore';

Next, inject AngularFirestore in your service via its constructor:

export class PolicyService {
  constructor(private firestore: AngularFirestore) { }
}

Next, add the .getPolicies method to retrieve the available policies from the Firestore collection:

getPolicies() {
    return this.firestore.collection('policies').snapshotChanges();
}

You also need to add the .createPolicy method to persist an insurance policy in the Firestore database:

createPolicy(policy: InsurancePolicy){
    return this.firestore.collection('policies').add(policy);
}

Next, you need to add the .updatePolicy method to update an insurance policy by its identifier:

updatePolicy(policy: InsurancePolicy){
    delete data.id;
    this.firestore.doc('policies/' + policy.id).update(policy);
}

Finally, you can add the .deletePolicy method to delete an insurance policy by its identifier:

deletePolicy(policyId: string){
    this.firestore.doc('policies/' + policyId).delete();
}

Creating the Component for making CRUD Operations

After creating the model and service for create, read, update and delete insurance policies, you now need to create the component for creating, updating, deleting and displaying them:

Using Angular CLI v7 run the following command to generate a component:

$ ng g c policy-list

Now, open the src/app/policy-list/policy-list.component.ts file and update it accordingly:

import { Component, OnInit } from '@angular/core';
import { PolicyService } from 'src/app/policy.service';
import { Policy } from 'src/app/policy.model';

@Component({
  selector: 'policy-list',
  templateUrl: './policy-list.component.html',
  styleUrls: ['./policy-list.component.css']
})
export class PolicyListComponent implements OnInit {

  policies: Policy[];
  constructor(private policyService: PolicyService) { }

  ngOnInit() {
    this.policyService.getPolicies().subscribe(data => {
      this.policies = data.map(e => {
        return {
          id: e.payload.doc.id,
          ...e.payload.doc.data()
        } as Policy;
      })
    });
  }

  create(policy: Policy){
      this.policyService.create(policy);
  }

  update(policy: Policy) {
    this.policyService.update(policy);
  }

  delete(id: string) {
    this.firestore.doc('policies/' + id).delete();
  }
}

Updating the Component Template

Now let's update the component's template to display insurance policies and also display buttons that can be used to create, update and delete policies:

Open the src/app/policy-list.component.html file and add the following HTML code:

<table>
  <thead>
    <th>Number</th>
    <th>Created At</th>
    <th>Expire At</th>
    <th>Amount</th>
  </thead>
  <tbody>
    <tr *ngFor="let policy of policies">

      <td>{{policy.policyNumber}}</td>
      <td>{{policy.creationDate}}</td>
      <td>{{policy.expireDate}}</td>
      <td>{{policy.policyAmount}}</td>
      <td>
          <button (click)="delete(policy.id)"/>
      </td>
    </tr>
  </tbody>
</table>

Below the <table> markup, you can also add a form to create an insurance policy.

Conclusion

In this tutorial, we've seen how to add CRUD operations to your Angular 7 project that allow you to create, read, update and delete data from a Firebase/Firestore database.


comments powered by Disqus