Angular 9|8 CRUD Operations using Firebase and Firestore Database in Angular Application Tutorial

In this post, we will implement the Firebase database in Angular 9 project. Firebase provides a cloud-based service Firestore, it is a NoSQL database that is very fast and easy to create and maintain.

In our example app, we will have Database CRUD operations which are commonly known as Create, Delete, Update, and Delete. These are the basic database operation which is used in most of the real-world application. To keep out app simple to understand we will not have routing.

Let’s start with our Angular 9 Firestore application which will have a Students data to perform CRUD operations.

Also See: Firestore CRUD Operation in Ionic 4 Application

Create a new Angular 9 project

$ ng new Angular9Firestore
$ cd Angular9Firestore

then for Routing select no as in this application we will not use create any new component, for styling we choose SCSS.

Create a Firebase Project

If you already having any Firebase project, you can use that or follow these steps to create one and enable Firestore database. After creating a Firebase project we will use credentials in our Angular Application.

 

Step 1) Visit Firebase here then click on Get Started if you have not created an account yet.

 

Step 2) Click on "Add project" then enter app related information click on "create"

 

Step 3) Next click on "Web App" icon to get configuration text with app secret info which we will add in our Application to communicate with services related to this Firebase project.

 

Step 4) Then enable Firestore Database service in your Firebase project.

Click on "Database" in the left sidebar, then click on "+ Add collection" enter name "Students" you can add anything you want. Here we are creating example data for Students. Then hit "Next"

On next screen delete the record on focus for this example or you can enter any dummy row data. We will add directly from App. After deleting then hit Save

Now we have Firebase project and Firestore Database with a collection "Students" is ready, the next step is to connect our Application with Firebase and Firestore Database.

Adding Firebase in Angular Application

Now open the Environment file at location "~Angular9Firestore/src/environments/environment.ts" then add Firebase project credentials as shown below

export const environment = {
  production: false,
  firebase: {
    apiKey: "YOUR_apiKey",
    authDomain: "YOUR_authDomain",
    databaseURL: "YOUR_databaseURL",
    projectId: "YOUR_projectId",
    storageBucket: "YOUR_storageBucket",
    messagingSenderId: "YOUR_messagingSenderId"
  }
 };

In app's main module file we will import Firebase and Initialize firebase with environment credentials

Install Firebase in Application

Install Firebase SDK and @angular/fire package by running below CLI command

$ npm install --save firebase @angular/fire

In app's main module file we will import Firebase and Initialize firebase with environment credentials

Replace below code in you app.module.ts file

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';


import { AngularFireModule } from '@angular/fire';
import { AngularFireDatabaseModule } from '@angular/fire/database';
import { environment } from '../environments/environment';
import { AngularFirestoreModule } from '@angular/fire/firestore';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,

    AngularFireModule.initializeApp(environment.firebase),
    AngularFirestoreModule,
    AngularFireDatabaseModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

by following the above steps your application is connected with Firebase and ready to perform CRUD operation on Firestore Database.

Create a Service with Firestore CRUD methods

Now create a service with CRUD operation methods. Service methods can be used anywhere without rewriting again and again.

Create new service "~Angular7Firestore/src/app/service/crud.service.ts", having the following methods

create_NewStudent: Create a new record in the specified collection using add method
read_Students: Call snapshotChanges method which will get records and also subscribe it to get updates
update_Student: Update record by taking ID then calling update method
delete_Student: Call delete method by taking record id
Replace below code in the crud.service.ts file
import { Injectable } from '@angular/core';

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

@Injectable({
  providedIn: 'root'
})
export class CrudService {

  constructor(
    private firestore: AngularFirestore
  ) { }


  create_NewStudent(record) {
    return this.firestore.collection('Students').add(record);
  }

  read_Students() {
    return this.firestore.collection('Students').snapshotChanges();
  }

  update_Student(recordID,record){
    this.firestore.doc('Students/' + recordID).update(record);
  }

  delete_Student(record_id) {
    this.firestore.doc('Students/' + record_id).delete();
  }
}

The final step is to create a page for User Interaction where we can create a new record and can view all rows available in the collection.

A user can also click on Edit and Delete buttons to perform record actions. In edit mode, the user can Cancel or Update changes.

To keep tutorial simple we will update the existing home component which is created by default app component template.

app.component.ts

<!--The content below is only a placeholder and can be replaced.-->
<div class="container">

  <h1 style="margin-top: 25px;">
    {{title}}
  </h1>

  <div class="row" style="margin-top: 25px;">
    <div class="col-md-3">
      <input type="text" class="form-control" [(ngModel)]="studentName" placeholder="Name">
    </div>
    <div class="col-md-3">
      <input type="text" class="form-control" [(ngModel)]="studentAge" placeholder="Age">
    </div>
    <div class="col-md-3">
      <input type="text" class="form-control" [(ngModel)]="studentAddress" placeholder="Address">
    </div>
    <div class="col-md-3">
      <button type="button" (click)="CreateRecord()" [disabled]="!studentName || !studentAge || !studentAddress" class="btn btn-primary">+
        Create Student</button>
    </div>
  </div>
  <div class="row" style="margin-top: 25px;">
    <div class="col-md-3">
      <div class="card" style="width: 18rem;" *ngFor="let item of students">
        <div class="card-body" *ngIf="!item.isEdit; else elseBlock">
          <h5 class="card-title">{{item.Name}}</h5>
          <h6 class="card-subtitle mb-2 text-muted">Age: {{item.Age}} Years</h6>
          <p class="card-text">Address: {{item.Address}}</p>
          <a href="#" class="card-link" (click)="EditRecord(item)">Edit</a>
          <a href="#" class="card-link" (click)="RemoveRecord(item.id)">Delete</a>
        </div>
        <ng-template #elseBlock>
          <div class="card-body">
            <h5 class="card-title">Edit</h5>
            <div class="form-group">
              <div class="row">
                <div class="col-md-12">
                  <input type="text" class="form-control" [(ngModel)]="item.EditName" placeholder="Edit Name">
                </div>
                <div class="col-md-12">
                  <input type="text" class="form-control" [(ngModel)]="item.EditAge" placeholder="Edit Age">
                </div>
                <div class="col-md-12">
                  <input type="text" class="form-control" [(ngModel)]="item.EditAddress" placeholder="Edit Address">
                </div>
              </div>
            </div>

            <a href="#" class="card-link" (click)="item.isEdit = false">Cancel</a>
            <a href="#" class="card-link" (click)="UpdateRecord(item)">Update</a>
          </div>
        </ng-template>
      </div>
    </div>
  </div>


</div>

app.component.ts

import { Component, OnInit } from '@angular/core';

import { CrudService } from './service/crud.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent  implements OnInit {
  title = 'Firestore CRUD Operations Students App';

  students: any;
  studentName: string;
  studentAge: number;
  studentAddress: string;

  constructor(private crudService: CrudService) { }

  ngOnInit() {
    this.crudService.read_Students().subscribe(data => {

      this.students = data.map(e => {
        return {
          id: e.payload.doc.id,
          isEdit: false,
          Name: e.payload.doc.data()['Name'],
          Age: e.payload.doc.data()['Age'],
          Address: e.payload.doc.data()['Address'],
        };
      })
      console.log(this.students);

    });
  }

  CreateRecord() {
    let record = {};
    record['Name'] = this.studentName;
    record['Age'] = this.studentAge;
    record['Address'] = this.studentAddress;
    this.crudService.create_NewStudent(record).then(resp => {
      this.studentName = "";
      this.studentAge = undefined;
      this.studentAddress = "";
      console.log(resp);
    })
      .catch(error => {
        console.log(error);
      });
  }

  RemoveRecord(rowID) {
    this.crudService.delete_Student(rowID);
  }

  EditRecord(record) {
    record.isEdit = true;
    record.EditName = record.Name;
    record.EditAge = record.Age;
    record.EditAddress = record.Address;
  }

  UpdateRecord(recordRow) {
    let record = {};
    record['Name'] = recordRow.EditName;
    record['Age'] = recordRow.EditAge;
    record['Address'] = recordRow.EditAddress;
    this.crudService.update_Student(recordRow.id, record);
    recordRow.isEdit = false;
  }

}

Conclusion: Finally, we have created an Angular application using Firebase service to implement CRUD operations.

6 thoughts on “Angular 9|8 CRUD Operations using Firebase and Firestore Database in Angular Application Tutorial”

  1. Christopher Paixão

    Thank you, your class helped me a lot.
    I used the tutorial to create a comments page, I can create and list comments. How can I do to list the comment by post? It is listing all comments in all posts. Thank you

  2. Great work and easy to understand. How can a student-details component be integrated to hold details of each student.

    Thanks

    1. Hi Kennedy,
      For showing details of a single student you can add the following method in crud service

      detail_of_Student(recordID) { return this.firestore.collection('Students').doc(recordID).get(); }

      For showing details on another page you need to pass student id via Routing parameter to other component/ detail page and call detail_of_Student method from details component with a Router parameter ID

      In details, component just add following method and pass ID

      GetStudent(recordRow){ this.crudService.detail_of_Student(recordRow.id).subscribe(data => { console.log(data.data()); }) }

  3. Charl van der merwe

    thank you for this! you helped a total novice really get going with getting documents from fire base!

  4. this works good…. could you make form with image upload? i can’t combine two different tutorial in your website ahaha.

Leave a Comment

Your email address will not be published. Required fields are marked *