Firebase CRUD Operations in Angular Part – II

In this article, we create Components to store, get, update, delete data in Firebase. In the last article, we saw how to set up the firebase account and database setup. Then we have created a service that is communicated with firebase and angular.
Demo User Add/Edit/Delete Firebase
4) Generate Angular Components for Adding, Updating & Creating Users Data

//add user
ng generate component add-user

//edit user
ng generate component edit-user

//user listing
ng generate component user-list

5)After generating the component we need to set up in the routing to the component. Display in the below code.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

// Use RouterModule, Routes for activating routing in angular
import { RouterModule, Routes } from '@angular/router';

// components 
import { AddUserComponent } from './add-user/add-user.component';
import { UserListComponent } from './user-list/user-list.component';
import { EditUserComponent } from './edit-user/edit-user.component';

// Routes array define component along with the path name for url
const routes: Routes = [
  { path: '', redirectTo: '/register-user', pathMatch: 'full' },
  { path: 'register-user', component: AddUserComponent },
  { path: 'view-user', component: UserListComponent },
  { path: 'edit-user/:id', component: EditUserComponent }

// Import RouterModule
  imports: [CommonModule,RouterModule.forRoot(routes)],
  exports: [RouterModule],
  declarations: []
export class AppRoutingModule { }

After adding the Router configration we need to active router service and layout in the “app.component.html” file. display in the below code.

<!-- Top navigation -->
<nav class="navbar navbar-default fixed-top bg-default flex-md-nowrap p-0 shadow">
  <a class="navbar-brand col-sm-3 col-md-2 mr-0" routerLink="/register-user">
    <span class="dasboard-text">Dashboard</span>

<!-- Sidebar navigation -->
<div class="container-fluid">
  <div class="row">
    <nav class="col-md-2 d-md-block bg-light sidebar">
      <div class="sidebar-sticky">
        <ul class="nav flex-column">

          <li class="nav-item">
            <a class="nav-link" routerLink="/register-user" routerLinkActive="active">
              <i class="fas fa-plus"></i>Add User

          <li class="nav-item">
            <a class="nav-link" routerLink="/view-user" routerLinkActive="active">
              <i class="fas fa-list-ul"></i>Users List

    <!-- Main content -->
    <main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4">
      <div class="inner-adjust">


        <!-- Footer -->


6) Display the notification for alert notification for success and error we use NGX-Toastr module. Installing module using the below command.

//instal module
npm install ngx-toastr --save
npm install @angular/animations --save

after install we need to importa in the app.module file and also import css in our angular.json for style.

//angular.json file.

"styles": [
  "node_modules/ngx-toastr/toastr.css" // ngx-toastr's css

import { ToastrModule } from 'ngx-toastr';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

  imports: [
    BrowserAnimationsModule, // required animations module
    ToastrModule.forRoot() // ToastrModule added

Now we can use these in our component. How to use in our component “ngx-toastr” display in the below code.

//need to import ngx toaster service
import { ToastrService } from 'ngx-toastr';

export class exampleComponent {
  constructor(private toastr: ToastrService) {}

  successNotification() {
    this.toastr.success('Successfully user added.');

To know more about API and option for the ngx-toaster Click here to their main documentation
7) Let’s create a user form using Reactive Form and store that data in firebase in our add-user component.
Let’s open “add-user.component.ts” we need to import the firebase service, reactive form modules.

import { CrudService } from '../shared/crud.service';    // CRUD services API
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms'; // Reactive form services
import { ToastrService } from 'ngx-toastr'; // Alert message 

Display below the full code for the add user form in firebase. we create “add-user.component.ts” we need to add the formbuilder for the form set data. display the form in “add-user.component.html” file display in the below code.

“add-user.component.ts” File

import { Component, OnInit } from '@angular/core';
import { CrudService } from '../shared/crud.service';    // CRUD services API
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms'; // Reactive form services
import { ToastrService } from 'ngx-toastr'; // Alert message using NGX toastr

  selector: 'app-add-user',
  templateUrl: './add-user.component.html',
  styleUrls: ['./add-user.component.css']

export class AddUserComponent implements OnInit {
  public userForm: FormGroup;  // Define FormGroup to user form
    public crudApi: CrudService,  // CRUD API services
    public fb: FormBuilder,       // Form Builder service for Reactive forms
    public toastr: ToastrService  // Toastr service for alert message
  ) { }

  ngOnInit() {
    this.crudApi.GetUsersList();  // Call GetStudentsList() before main form is being called
    this.usForm();              // Call User form when component is ready

  // Reactive student form
  usForm() {
      firstName: ['', [Validators.required, Validators.minLength(2)]],
      lastName: [''],
      email: ['', [Validators.required, Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')]],
      mobileNumber: ['', [Validators.required, Validators.pattern('^[0-9]+$')]]

  // Accessing form control using getters
  get firstName() {
    return this.userForm.get('firstName');

  get lastName() {
    return this.userForm.get('lastName');

  get email() {
    return this.userForm.get('email');

  get mobileNumber() {
    return this.userForm.get('mobileNumber');

  // Reset user form's values
  ResetForm() {
  submitUSerData() {
    this.crudApi.AddUser(this.userForm.value); // Submit user data using CRUD API
    this.toastr.success(this.userForm.controls['firstName'].value + ' successfully added!');
    this.ResetForm();  // Reset form 


“add-user.component.html” File

<div class="pt-3 pb-2 mb-3 border-bottom">
  <h1 class="h2">Add User</h1>
  <p class="custom-text">CRUD app for <strong>user record management system</strong></p>

<!-- USer form -->
<form [formGroup]="userForm" (ngSubmit)="submitUSerData()" novalidate>
  <div class="row">
    <div class="col-lg-5 col-md-12 col-sm-12">
      <div class="row">

        <div class="col-md-12 mb-3">
          <label>First name</label>
          <input type="text" formControlName="firstName" class="form-control" required>
          <!-- Showing errors using getter method -->
          <p *ngIf="firstName.touched && firstName.invalid" class="error"><sup>*</sup>Please enter atleast first name</p>
          <p *ngIf="firstName.errors?.minlength" class="error"><sup>*</sup>Name shouldn't be less than 2 words</p>

        <div class="col-md-12 mb-3">
          <label>Last name</label>
          <input type="text" formControlName="lastName" class="form-control">


      <div class="row">
        <div class="col-md-12 mb-3">
          <input type="email" formControlName="email" class="form-control" required>
          <!-- Showing errors using getter method -->
          <p *ngIf="email.touched && email.invalid" class="error"><sup>*</sup>Please provide email</p>
          <p *ngIf="email.errors?.pattern" class="error"><sup>*</sup>Please enter correct email</p>

        <div class="col-md-12 mb-3">
          <label>Mobile number</label>
          <input type="text" formControlName="mobileNumber" class="form-control" required>
          <!-- Showing errors using getter method -->
          <p *ngIf="mobileNumber.touched && mobileNumber.invalid" class="error"><sup>*</sup>Please provide contact
          <p *ngIf="mobileNumber.errors?.pattern" class="error"><sup>*</sup>Use numbers only


      <div class="form-group text-right">
        <button type="button" class="btn btn-secondary gap-right" (click)="ResetForm()">Reset</button>
        <button type="submit" class="btn btn-primary" [disabled]="!studentForm.valid">Add User</button>

</form><!-- USer form ends-->

In next article we discuss on how to display list of the users with pagination , edit and delete of the user added.

Spread the love
  • 5
  • 2

No Responses