You are on page 1of 8

CRUD (Create, Read, Update, Delete) Application using Fire store (Firebase)

1. Set Up Firebase Database


2. Create new Angular project
3. Install firebase to angular project
npm i --s firebase @angular/fire
4. Add firebase database details to Angular Project.
File: (environment.prod.ts)

firebaseConfig : {
apiKey: "AIzaSyDmYt52dYyTy1H0iuJ96fkiOY-qiWszm44",
authDomain: "firestorecrud-73178.firebaseapp.com",
databaseURL: "https://firestorecrud-73178.firebaseio.com",
projectId: "firestorecrud-73178",
storageBucket: "firestorecrud-73178.appspot.com",
messagingSenderId: "620422584742",
appId: "1:620422584742:web:b05429eea888e8d89b1767",
measurementId: "G-M31FYVZDHK"
}

5. Import the firebase configuration from environment.prod.ts to app.module.ts


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

@NgModule({
declarations: [
AppComponent,
EmployeesComponent,
EmployeeComponent,
EmployeeListComponent
],
imports: [
BrowserModule,
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFirestoreModule,
AngularFontAwesomeModule,
FormsModule,
BrowserAnimationsModule,
ToastrModule.forRoot()
],

6. Run the Application it should be no error in the console *Developer Mode.


7. Install Latest Bootstrap & Font Awesome through npm.
8. Add this css files into style.css in the src folder.
File: (style.css)

@import '~bootstrap/dist/css/bootstrap.min.css';
@import '~font-awesome/css/font-awesome.css';
9. Create one parent component inside app folder.
ng g c employees --spec=false
10. Create two child components inside employees folder
ng g c employees/employee --spec=false
ng g c employees/employee-list --spec=false

11. Create one folder inside src folder called shared


12. Create service.class inside shared folder
ng g s shared/employee --spec=false
13. Create model.class inside shared folder
ng g cl shared/employee --type=model

14. Edit app.component.html


<div class="container">
<app-employees></app-employees>
</div>

15. Edit employees.component.html


<div class="row">
<div class="col-md-5">
<app-employee></app-employee>
</div>
<div class="col-md-7">
<app-employee-list></app-employee-list>
</div>
</div>

16. Add property to employee class, inside employee.model.ts inside shared folder.
export class Employee {
id: string;
fullName: string;
empCode: string;
position: string;
mobile: string;
}

17. If the property is used in many components then add the property inside service.class inside
shared folder and inject the property to app.module.ts
File: (employee.service.ts)
export class EmployeeService {
formData: Employee;
constructor() { }

File: (app.module.ts)
import { EmployeeService } from './shared/employee.service';

providers: [EmployeeService],
File: (employee.component.ts)
import { EmployeeService } from 'src/app/shared/employee.service';

constructor(private service: EmployeeService)

18. Create form inside employee.component.html


<h1 class="display-4">EMP. Register</h1>
<form #form="ngForm" autocomplete="off" (submit)="onSubmit(form)">
<input type="hidden" name="id" #id="ngModel" [(ngModel)]="service.for
mData.id">
<div class="form-group">
<input name="fullName" #fullName="ngModel" [(ngModel)]="service.for
mData.fullName" class="form-control" placeholder="Full name" required>
<div *ngIf="fullName.invalid && fullName.touched" class="validation
-error">This field is required.</div>
</div>
<div class="form-group">
<input name="position" #position="ngModel" [(ngModel)]="service.for
mData.position" class="form-control" placeholder="Position">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<input name="empCode" #empCode="ngModel" [(ngModel)]="service.for
mData.empCode" class="form-control" placeholder="Emp. code">
</div>
<div class="form-group col-md-6">
<input name="mobile" #mobile="ngModel" [(ngModel)]="service.formD
ata.mobile" class="form-control" placeholder="Mobile">
</div>
</div>
<div class="form-group">
<button type="submit" [disabled]="form.invalid" class="btn btn-
lg btn-block btn-info">SUBMIT</button>
</div>

</form>

19. Import forms module into app.module.ts


import {FormsModule} from '@angular/forms';
20. Run the application and it will prompt error in the console, since not initialize the form
property inside employee.service.ts class

File: (employee.component.ts)

ngOnInit() {
this.resetForm();
}

resetForm (form? :NgForm){


if (form != null)
form.resetForm();
this.service.formData = {
id: null,
fullName: '',
position: '',
empCode: '',
mobile: '',
}
}

21. Add css to show field required inside employee


File: (employee.component.css)

input.ng-touched.ng-invalid{
border-color: #dc3545;
}

div.validation-error{
width: 100%;
margin-top: .25rem;
font-size: 80%;
color: #dc3545;
}
22. Function once user click Submit button
File: (employee.component.ts)

constructor(…private firestore: AngularFirestore…) { }

onSubmit(form: NgForm) {
let data = Object.assign({}, form.value);
delete data.id;
if (form.value.id == null)
{
this.firestore.collection('employees').add(data);
this.toastr.success('Submitted successfully', 'EMP. Register');
}
else
{
this.firestore.doc('employees/' + form.value.id).update(data);
this.toastr.warning('Updated successfully', 'EMP. Register');}
this.resetForm(form);
}

23. Check firebase the operation must be successful


24. Install toastr for Notification
npm install ngx-toastr –save
25. Import Toastr to employee.component.ts
File: (employee.component.ts)
import { ToastrService } from 'ngx-toastr';

26. Import inside angular.json


File: (angular.json)

"styles": [
"src/styles.css",
"node_modules/ngx-toastr/toastr.css",
"node_modules/font-awesome/css/font-awesome.css"
],

27. Import forms module to app.module.ts


File: (app.module.ts)

import { BrowserAnimationsModule } from '@angular/platform-


browser/animations';
import { ToastrModule } from 'ngx-toastr';

imports: [
BrowserModule,
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFirestoreModule,
AngularFontAwesomeModule,
FormsModule,
BrowserAnimationsModule,
ToastrModule.forRoot()
],

28. Import toastr into constructor


File: (employee.component.ts)
constructor(private toastr: ToastrService) { }

29. List the data from firebase to table in employee-list.html


File: (employee.service.ts
Add private parameter for firestore
constructor(private firestore: AngularFirestore) { }

Define the function to call data from firebase

getEmployees() {
return this.firestore.collection('employees').snapshotChanges();
}

30. Add parameter to employee-list.component.ts


constructor(private toastr: ToastrService) { }

31. Initialize the get value from firebase


ngOnInit() {
this.service.getEmployees().subscribe(actionArray => {
this.list = actionArray.map(item => {
return {
id: item.payload.doc.id,
...item.payload.doc.data()
} as Employee;
})
});
}

32. Declare new property inside employee-list.component.ts


list: Employee[];

33. Initialize get employees inside employee-list.component.ts


ngOnInit() {
this.service.getEmployees().subscribe(actionArray => {
this.list = actionArray.map(item => {
return {
id: item.payload.doc.id,
...item.payload.doc.data()
} as Employee;
})
});
}
34. Add table to html file employee-list.component.html
<table class="table table-hover">
<thead>
<th>Name</th>
<th>Position</th>
<th>Mobile</th>
<th></th>
</thead>
<tbody>
<tr *ngFor="let emp of list">
<td (click)="onEdit(emp)">{{emp.empCode}} - {{emp.fullName}}</td>
<td (click)="onEdit(emp)">{{emp.position}}</td>
<td (click)="onEdit(emp)">{{emp.mobile}}</td>
<td><a class="btn text-
danger" (click)="onDelete(emp.id)"><i class="fa fa-trash"></i></a></td>
</tr>
</tbody>
</table>

35. Check the employee-list table and it should be show the correct data from firebase
36. Edit the data in the employee-list component table
onEdit(emp: Employee) {
this.service.formData = Object.assign({}, emp);
}

37. Update the data


onSubmit(form: NgForm) {
let data = Object.assign({}, form.value);
delete data.id;
if (form.value.id == null)
{
this.firestore.collection('employees').add(data);
this.toastr.success('Submitted successfully', 'Employee. Register
', { timeOut: 950});
}
else
{
this.firestore.doc('employees/' + form.value.id).update(data);
this.toastr.warning('Updated successfully', 'Employee. Update', {
timeOut: 950});}
this.resetForm(form);
}
38. Delete the record operation import firestore property to constructor
File: (employee-list.component.ts)
constructor(private firestore: AngularFirestore) { }

39. Delete the record operation


File: (employee-list.component.ts)

onDelete(id: string) {
if (confirm("Are you sure to delete this record?")) {
this.firestore.doc('employees/' + id).delete();
this.toastr.error('Deleted successfully','Employee. Delete', { ti
meOut: 950});
this.resetForm();
}
}

40.

You might also like