In this post, we will implement the Firebase database in Angular 7 project. Firebase provides a cloud-based service Firestore, it is a NoSQL database which 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 7 Firestore application which will have a Students data to perform CRUD operations.
Create a new Angular 7 project
1 2 3 | $ ng new Angular7Firestore $ cd Angular7Firestore |
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 “~Angular7Firestore/src/environments/environment.ts” then add Firebase project credentials as shown below
1 2 3 4 5 6 7 8 9 10 11 12 | 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
1 2 | $ 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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 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 a new service “~Angular7Firestore/src/app/service/crud.service.ts“, having the following methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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 existing home component which is created by default app component template.
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | <!--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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | 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; } } |
this works good…. could you make form with image upload? i can’t combine two different tutorial in your website ahaha.
thank you for this! you helped a total novice really get going with getting documents from fire base!
Great work and easy to understand. How can a student-details component be integrated to hold details of each student.
Thanks
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 IDIn details, component just add following method and pass ID
GetStudent(recordRow){
this.crudService.detail_of_Student(recordRow.id).subscribe(data => {
console.log(data.data());
})
}
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
Easy to understand and super useful ! thanks