Creating CRUD App with Angular and Firebase Firestore

Creating new project with angular

we are building a phonebook application using angular and firebase cloud firestore database.

first we create a new angular project

ng new phonebook

Create Your Firebase Cloud FIrestore

visit https://firebase.google.com/ to start our project to create a database to save delete update our contact

Click on go to console and to add a new project

first.png

second.png

third.png

Now to work with firebase you will have to get your firebase configuration file

Since we will be working with angular we are working with web config

Click on the web icon on the project overview dashboard to get the config file

fourth.png

fifth.png

Now copy the firebase config object as shown the highlighted area below

sixth.png

On the firebase overview click on cloud firestore and create database

seven.png

On creating a database start a collection and follow the process till you create a database to use for the our phonebook application and the database looks like the image below to save phone contact in our application.

eight.png

Setup your environment.ts

Now open your angular app and goto environment.ts and paste the config inside as shown below, and replace the ** with your configuration object you get in the firebase

export const environment = {
  production: false,
  firebase:  {
    apiKey: "***",
    authDomain: "***",
    databaseURL: "***",
    projectId: "***",
    storageBucket: "***",
    messagingSenderId: "***",
    appId: "***",
    measurementId: "***"
  }
};

Installing and Setting up Firebase In your Angular

    ng add @angular/fire

Update your app.module.ts file and update your as shown below

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

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { AngularFireModule } from '@angular/fire';
import {AngularFirestoreModule } from '@angular/fire/firestore/';
import { environment } from 'src/environments/environment';
import { FormsModule } from '@angular/forms';

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

Generate service to perform our crud operation

ng g service service/services

Open service/services.ts and import AngularFirestore

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

Declare it in the constructor

constructor(public afs: AngularFirestore) { }

save contact the database

 saveContact(doc:string, data: phonebook){{
    return this.afs.collection(doc).add(data)
  }}

Getting all database data

getAllContacts(doc:string){
  return this.afs.collection(doc).valueChanges()
}

Get data by id from document

 getOneContact(doc:string, id:string){
    return  this.afs.doc<phonebook>(`${doc}/${id}`).valueChanges()
  }

Update document

   updateContact(doc:string, id:string, data: phonebook){
    return this.afs.doc(`${doc}/${id}`).update(data)
  }

Delete Data from our database

   deleteContact(doc:string, id:string){
    return this.afs.doc(`${doc}/${id}`).delete()
  }

Your service file looks like this after all the code have been completed

 import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { phonebook } from '../model/phonebook';

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

  constructor(public afs: AngularFirestore) { }

  saveContact(doc:string, data: phonebook){{
    return this.afs.collection(doc).add(data)
  }}

  getAllContacts(doc:string){
    return this.afs.collection(doc).valueChanges()
  }

  getOneContact(doc:string, id:string){
    return  this.afs.doc<phonebook>(`${doc}/${id}`).valueChanges()
  }

  updateContact(doc:string, id:string, data: phonebook){
    return this.afs.doc(`${doc}/${id}`).update(data)
  }

  deleteContact(doc:string, id:string){
    return this.afs.doc(`${doc}/${id}`).delete()
  }
}

Now we create a component for our phone book

ng g c home

home.html

 <div class="container" *ngIf="!edit">
    <div class="row">
        <h3>
            Phone Book
        </h3>
        <form action="">
            <div class="form-group">
                <label for="name">Name</label>
                <input type="text" class="form-control rounded-0" name="name" id="name" autocomplete="name" [(ngModel)]="contact.name">
            </div>
            <div class="form-group">
                <label for="name">Phone Number</label>
                <input type="number" class="form-control rounded-0" name="phone" id="phone" [(ngModel)]="contact.phone">
            </div>
            <div class="form-group">
                <button type="button" name="" id="" class="btn btn-success  btn-block rounded-0" (click) = "saveContact()">
                    Save Contact
                </button>
            </div>
        </form>
    </div>
</div>

In our home.ts we will import our service to be able to work with our firestore database

import { Component, OnInit } from '@angular/core';
import { phonebook } from '../model/phonebook';
import { ContactserviceService } from '../services/contactservice.service';

After we initialize our service on the constructor

 constructor(private service: ContactserviceService) { }

We can now save contact with our angularfirestore

saveContact(){
    this.service.saveContact('users',this.contact)
    .then(doc =>{
      doc.update({id: doc.id})
      console.log('registration successful')
    })
    .catch(err=> console.log(err))
  }
getAllcontacts(){
    this.allContact = this.service.getAllContacts('users')
  }

And the html for getting all the contact looks like below code

 <div class="row">
        <h3>Contact Lists</h3>
        <div class="contact-list">
            <ul>
                <li *ngFor="let contact of allContact | async">
                    {{contact.name}}
                    <br>
                    {{contact.phone}} <br>
                    <button (click)= "deleteContact(contact.id)">Delete</button>
                    <button (click)= "editButton(contact.id)">Update</button>
                </li>
            </ul>
        </div>
    </div>

The delete code is as below

  deleteContact(id:string){
    this.service.deleteContact('users', id)
    .then(()=>{
      console.log('successfully deleted')
    })
    .catch((err)=>{
      console.log(err)
    })
  }

To update contact

  updateContact(){
    this.service.updateContact('users', this.id, this.contact)
    .then((data)=>{
      console.log("successfully updated", data)
      this.edit = false
    })
    .then(()=>{
      this.contact = {name: "", phone: ""}
    })
    .catch(err => console.log(err))
  }
ng serve

For reference visit github repo