Angular 5 CRUD Operations With Firebase - CodAffection

Angular 5 CRUD Operations With Firebase

Angular CRUD with Firebase

This is a step by step tutorial on how to implement Angular 5 CRUD Operations with Firebase project. So let’s demonstrate Create Read Update and Delete Operations in an Angular 5 project. In one of my other article we discussed on CRUD Operations in Angular 5 with Web API.

Following tools and modules are used for this project :

– Angular CLI
– Angular 5
– Firebase project
– Firebase and AngularFire2 (npm packages)
– ngx-Toastr (npm package)
– Bootstrap and Font-Awesome Icons
– VS Code Editor

we assume that you have installed required packages and software for angular 5 development.

Create Angular 5 Application

In-order to create an Angular 5 application, you can use following Angular CLI command


ng new angular5firebasecrud

it will create an angular 5 application in the current directory and install some default npm packages.
To run this application


# switch to project folder
cd angular5firebasecrud
# run the project
ng serve --open

it will open this project in your default web browser from 4200 port.

Create Firebase Project

Goto Firebase Console. it will automatically log in with your gmail account.

Click On Add Project. it will open a pop-up window, inside that name your project, then click on Add Project button.After creating firebase project, Project Dashboard / Project Overview will be opened like this.

firebase project overview - click on Add Firebase to your web app

Click on ‘Add Firebase to your web app’, it will open another popup window with firebase project configuration. copy config object from there.

Copy Firebase Configuration Details

then past inside environment.ts  file as firebaseConfig.

Change FirebaseDB Permission

Goto Database > Rules Tab (if not showing click on ‘get started’)

Set following read & write permission

Install Firebase & Angularfire2 Modules

Firebase and Angularfire2 are official packages to interact with firebase project from angular applications.

In-order to install these packages use following npm commands


npm install firebase@4.6.1 angularfire2@5.0.0-rc.3 --save

Open appmodule.ts file, then initialize firebase module with firebase project configuration.

Add Required Angular 5 CRUD Components, Model and Service Classes

Now we need to add 3 components, to add angular components you can use following Angular-CLI commands


# from root component
ng g c employees

remaining two components will be child components for this employees component.


//switch to parent component directory
cd src\app\employees
//create child components
ng g c employee
ng g c employee-list

Open app.module.ts file, Add newly added components into declarations array.

Let’s Start the Design

We’ll use Bootstrap and Font-Awesome Icons For Application Design. So first of all add CDN reference for the style sheets inside index.html .

Update app.component.html as follows

Add Following to employees.component.html file.

We need Model and Services to design remaining child components.

Create Service and Model Classes

To create these classes let’s add a new folder with name shared inside employees folder (/src/app/employees/ ).

Now create employee model class


# switch to shared folder
cd src\app\employees\shared
# create employee model class
ng g class employee --type=model
# create employee service class
ng g s employee

In this application, we deals with employee details like

  • Full Name
  • Position
  • Office Location
  • Salary

So let’s add properties corresponding to these employee’s details inside employee.model.ts file.

$key is used to store unique key automatically generated by firebase DB when we insert a new record.

Inside the service file we will do Firebase CRUD Operation as follows

EmployeeService contains selectedEmployee property of the type employee model class Employee,to store currently active employee details. employeeList variable store all the employee records from Firebase DB.

In-order to interact with firebase project we have injected AngularFireDatabase as firebase. getData function initialize employeeList from firebase node ’employees’. we will store employee records under this node. rest of the functions are self explanatory.

Using selectedEmployee property we can design form for insert and update operation inside employee component,
In-order to list inserted employees we can use employeeList property in employee-list component. So first of all we have to Inject this service class inside child components. Before that we have to discuss our application structure.

Application Structure


● src
+---● app
|   +--● employees
|   |  |--employees.component.ts|.html|.css
|   |  +--● employee (employee form)
|   |  |  |--employee.component.ts|.html|.css
|   |  |
|   |  +--● employee-list (list inserted employees)
|   |  |  |--employee-list.component.ts|.html|.css
|   |  |
|   |  +--● shared
|   |     |--employee.service.ts
|   |     |--employee.model.ts
|   |
|   |--app.module.ts (configured firebase connection)
|
+---● environments  
|   |--environment.ts (saved firebase connection details)
|
|--index.html (cdn path for bootstrap and font awesome icon)

This our application structure, component employees will be the parent component for employee and employee-list component.

We are going to inject EmployeeService inside the Parent Component Employees. and there by we can access the same injected service instance from child components Employee and Employee-List. so whenever we make make changes in one child component same change can be seen from other child component also.

Inject Employee Service in Components :

first of all inject the service class inside parent component Employees

To inject a class inside a component , mention the class inside component providers array and then create private parameter inside component constructor.

Now we can use this injected instance in child components, for that you can do this, Inside employee.component.ts file

Inside employee-list.component.ts file

Angular 5 CRUD Operations Form

We’ll create an employee form to implement Insert and Update Operation with employee Component. For that, let’s create a Template Driven Form(TDF) using selectedEmployee property from injected EmployeeService Class.

So first of all we have to import FormsModule in appmodule.ts file.

You can use following html in employee.component.html file.

and this employee form with data looks like this

Form to implement angular 5 CRUD Operations

This form is a collection of label – text box pair with Submit and Reset button. We have an extra hidden field to store $key of current employee. Same form is used for Insert and Update Operation.

Form Validation

required attribute is set to name text box, so employee name is mandatory to submit this form. When name text-box is invalid, ng-invalid and ng-dirty classes are added to it. So based on these we have implemented form validation.

when name is empty, employee form as whole is not valid so we add conditional disable attribute to Submit Button.

to show validation error indication we’ll show red border around the text box using CSS. Here is the complete css rules for this application


input.ng-invalid.ng-dirty{
    border: 1px solid red;
}
button:hover,a.btn:hover{
    cursor: pointer;
   }

Insert, Update and Reset Operation

Inside employee.component.ts file we’ll write code for Insert and Update Operation. Before that I’m going to install ngx-toastr fromnpm package, this package helps us to show notification message inside angular applications.

ngx-toastr installation

In-order to install the package, you can use following npm command.


npm install ngx-toastr --save

then add ToastrModule inside app.module.ts file.

Open .angular-cli.json, then update styles array.

Now you can add following code inside employee component.

restForm() function is used reset form controls value to initial stage, we called this function from reset button click event and from ngOnint  Lifecycle Hook to initialise the form.

Inside the form submit event function OnSubmit, we implement both insert and update operation based on $key value. To show the success message, we use ToastrService class object tostr.

List Inserted Records and Delete Operation

Using employee-list component, we’ll list all inserted employees and then implement Delete Operation.

you can add following inside employee-list component.

Inside this we have injected EmployeeService and ToastrService Classes. Also we created an Employee array employeeList. Inside the ngOnint  Lifecycle Hook, we subscribe to firebase db collection and we store employee records inside an array. Using this array variable, we will display inserted employees inside employee-list component.

employee-list.component.html looks like this.

Component design will look like this

show employee records inside an html table

when we click on pencil button, it will call onEdit() function to populate the corresponding record inside the employee form, after changing user’s details,he can update record as we discussed before(inside employee component).Using trash icon we implemented delete operation with onDelete()  function.

Download Project Source Code : https://goo.gl/83tyjH

Video Tutorial

Thanks for the visit, hope you liked it, let me know your comments.

51 thoughts on “Angular 5 CRUD Operations With Firebase”

  1. Outstanding tutorial, only wish it had been updated to Angular 8/9, a lot of CRUD Tutorials on the web this is one of the best but sadly outdated.

  2. I am getting this error,What i have to do now?
    ERROR in node_modules/angularfire2/angularfire2.d.ts(3,10): error TS2305: Module ‘”C:/Users/admin/crud-app/node_modules/rxjs/Subscription”‘ has no exported member ‘Subscription’.

  3. Hello,
    I am getting below error
    “node_modules appears empty, you may need to run `npm install”.
    I tried npm install but again same issue.

  4. Mangesh Jamdade

    Hi. This tutorial helps me to create my first angular app. But I am stuck on showing data from firebase. I got this error. “Property ‘toJSON’ does not exist on type ‘DatabaseSnapshot’ ” in src/app/employees/employee-list/employee-list.component.ts. I think I am missing some part of code. Thank you in advance

  5. Swapnil Borode

    Man Awesome tutorial !!! Great job…:)…..I have gone through many sites of Angular 5 CRUD Application, none of them provided this much accurate approach.
    Cheers !!!

  6. Getting error
    ERROR TypeError: Cannot read property ‘push’ of undefined
    at EmployeeService.insertEmployee (employee.service.ts:20)
    at EmployeeComponent.onSubmit (employee.component.ts:24)
    at Object.eval [as handleEvent] (EmployeeComponent.html:1)
    at handleEvent (core.js:13589)
    at callWithDebugContext (core.js:15098)
    at Object.debugHandleEvent [as handleEvent] (core.js:14685)
    at dispatchEvent (core.js:10004)
    at eval (core.js:12343)
    at SafeSubscriber.schedulerFn [as _next] (core.js:4354)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:243)
    View_EmployeeComponent_0 @ EmployeeComponent.html:1
    proxyClass @ compiler.js:14659
    DebugContext_.logError @ core.js:15038
    ErrorHandler.handleError @ core.js:1510
    dispatchEvent @ core.js:10008
    (anonymous) @ core.js:12343
    schedulerFn @ core.js:4354
    SafeSubscriber.__tryOrUnsub @ Subscriber.js:243
    SafeSubscriber.next @ Subscriber.js:190
    Subscriber._next @ Subscriber.js:131
    Subscriber.next @ Subscriber.js:95
    Subject.next @ Subject.js:56
    EventEmitter.emit @ core.js:4322
    NgForm.onSubmit @ forms.js:5764
    (anonymous) @ EmployeeComponent.html:1
    handleEvent @ core.js:13589
    callWithDebugContext @ core.js:15098
    debugHandleEvent @ core.js:14685
    dispatchEvent @ core.js:10004
    (anonymous) @ core.js:10629
    (anonymous) @ platform-browser.js:2628
    ZoneDelegate.invokeTask @ zone.js:421
    onInvokeTask @ core.js:4751
    ZoneDelegate.invokeTask @ zone.js:420
    Zone.runTask @ zone.js:188
    ZoneTask.invokeTask @ zone.js:496
    invokeTask @ zone.js:1540
    globalZoneAwareCallback @ zone.js:1566
    EmployeeComponent.html:1 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 0, nodeDef: {…}, elDef: {…}, elView: {…}}

  7. Hi !

    Thank you for this great tutorial.
    I don’t understand the part “Inject Employee Service in Components”
    Why do we import the service in employees component ?
    If I just import the service in employee and employee-list component, It work as well.

    1. service class is imported to components employees,employee and employee-list. But only for parent component (employees), we have a providers array for the service. because of that same instance of service is shared in child components(employee and employee-list). So changes made from one child component can be accessed from other component.

  8. Hi great tutorial!!! But, how are data passed in the form when the edit button is pressed? I modified a bit the code to show only the list and after the edit button is pressed to show the form but it is empty.

  9. I admire you guys, it works well!! i appreciate this material on angular 5… in fact it’s my first ever material.
    But when i store an employee, the toast displays at the left downside with no css as it does in your demo. could u guess why please?!

    1. Thanks for the comment, Sorry I forgot to mention toastr style-sheet.
      Open .angular-cli.json then add following update styles array as follows
      “styles”: [
      “styles.css”,
      “../node_modules/ngx-toastr/toastr.css”
      ]

  10. Could you explain me how I can implement the same model but in every item I want to have another list. How can I change my .subscribe() method to populate also the sub-lists?

  11. I have an issue with my edit function, it doesn’t seem to do anything if I click it and I’ve checked to make sure everything is correct

  12. this example works perfectly.thanks for the information.Can someone help me how to perform queries such as i like to filter the names of the employees whose salary is greater than 5000.

  13. I’m getting an error on running ng serve –open

    It claims it “Cannot find module ‘bluebird'”

    Any suggestions?

  14. Thanks for this great tutorial. works perfectly. Have a question: I am using angular material for my form and I have used mat-select and mat-option for multiple selection. For editing, how can I show the currently selected options on the form??

  15. If I want get user by Id, exemple:
    getUser(key: string) {
    let teste = { key: ”, name: ‘ratal’ };
    // console.log(key);

    // console.log(this.firebase.object(key));
    }

    how I get user by Id please, someone ?

Leave a Comment

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

Scroll to Top
2 Shares
2 Shares
Share via
Copy link