Google provides a Firebase service where you can use the backend of an application. The database (Firebase Realtime Database) is considered a NoSQL database where data is stored similarly to a JSON document. In this article, you learn how to create a mobile web app using Angular and Firebase.
If you are started with Angular and want to use Firebase for Backend development. First, we need to set up Firebase to make it usable. Follow the below-given steps to set up and use Firebase in order to build an interactive application. You can use Firebase in Angular and create an interactive web application.
Step 1: Setting up Firebase
Source: blog.jscrambler.com
Singin to Firebase Console and set up an environment.
After signing in, click on the ‘Add project’ option to create a new project.
You’ll be asked to enter the project’s name. Here we will name our project ‘js-new app-demo.’
Source: blog.jscrambler.com
Next, it will ask you whether you want to enable Google Analytics for this new project or not. Here we will disable it because it is not needed in this guide.
Click on the Create Project and then the continue button to navigate to the below-mentioned screen.
Step 2: Register your application
After creating a new project, you need to register your application.
Enter an application name and tap on the register option.
Once you have registered an application, you can now see the Firebase app config.
The above-mentioned configuration application in the Angular application will be connected to the Firebase database.
Tap on the ‘Firestore Database’ link which is mentioned on the left side of the menu.
Source: blog.jscrambler.com
Step 3: Create a Database
Create a new database in the ‘firestone’ by clicking on the new create database button.
Once you have navigated to Cloud firestore data option, tap on the Start collection button in order to create a new collection.
Source: blog.jscrambler.com
Enter the collection name as shown in the below-given image. After that tap on the add a new document to the collection.
Create two field names to save the ‘name’ and ‘personalInfo’ of the user.
Source: blog.jscrambler.com
Step 4: Connect Angular to Firebase
Now that you have created a database by using Firebase in Angular, next you need to connect the Angular app to Firebase.
Create an Angular app using Angular CLI.
ng new angular-firebase
Install ‘firebase’ and @angular/fire to the new Angular project.
npm install firebase @angular/fire
Import two Angular modules which are ‘AngularFirestoreModule’ and ‘AngularFireModule.’
import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';
Below is what the app.module.ts file looks like.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
AngularFireModule.initializeApp({
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "js-scrambler-demo-app.firebaseapp.com",
projectId: "js-scrambler-demo-app",
storageBucket: "js-scrambler-demo-app.appspot.com",
messagingSenderId: "xxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
}),
AngularFirestoreModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Create an instance in the construct method by importing ‘AngularFirestore’ from the ‘app.component.ts.’
import { AngularFirestore } from '@angular/fire/firestore';
constructor(private store: AngularFirestore){}
Name the method known as getAll in order to receive all the collected data from Firebase.
ngOnInit(){
this.getAll();
}
getAll(){
this.store.collection('userInfo').snapshotChanges().subscribe((response) => {
console.log('reponse ', response);
})
}
Save all the changes and you will be able to get all the details of userInfo in your console browser. This shows that we have successfully connected the Angular app to the database.
Install the required dependencies and Bootstrap to the new Angular project.
npm install bootstrap jquery popper.js
Add the below-given script to the ‘angular.json’ file under the key named architec> build.
"styles": [
"src/styles.css",
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/popper.js/dist/umd/popper.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
]
All the collected data in ‘getAll’ need to parse all the data and render to the user interface.
Define the variable named dataSource in the app.component.ts. This will be used to render the data collected in tabular form.
dataSource : any;
Iterate each data from the collected snapshotChanges and receive the required information.
This will require the name, personal info, and document ID from each of the documents. You can get the required information from payload.doc which we can parse as shown below.
getAll(){
this.store.collection('userInfo').snapshotChanges().subscribe((response) => {
this.dataSource = response.map(item =>
Object.assign({id : item.payload.doc.id}, item.payload.doc.data())
);
})
}
Now that we have all the data, it’s time to render the data to the user interface. Add the below-given HTML to app.component.html to render the data.
<div class="container m-100 main">
<div>
<svg data-bs-toggle="modal" (click)="openDialog()" xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="currentColor" class="bi bi-cloud-plus-fill" style="cursor: pointer;" viewBox="0 0 16 16">
<path d="M8 2a5.53 5.53 0 0 0-3.594 1.342c-.766.66-1.321 1.52-1.464 2.383C1.266 6.095 0 7.555 0 9.318 0 11.366 1.708 13 3.781 13h8.906C14.502 13 16 11.57 16 9.773c0-1.636-1.242-2.969-2.834-3.194C12.923 3.999 10.69 2 8 2zm.5 4v1.5H10a.5.5 0 0 1 0 1H8.5V10a.5.5 0 0 1-1 0V8.5H6a.5.5 0 0 1 0-1h1.5V6a.5.5 0 0 1 1 0z"/>
</svg>
</div>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Personal Info</th>
<th>
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of dataSource; let i = index;">
<th scope="row">{{i+1}}</th>
<td>{{item.name}}</td>
<td>{{item.personalInfo}}</td>
<td class="action">
<svg (click)="edit(item.id)" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pencil-fill" viewBox="0 0 16 16">
<path d="M12.854.146a.5.5 0 0 0-.707 0L10.5 1.793 14.207 5.5l1.647-1.646a.5.5 0 0 0 0-.708l-3-3zm.646 6.061L9.793 2.5 3.293 9H3.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.207l6.5-6.5zm-7.468 7.468A.5.5 0 0 1 6 13.5V13h-.5a.5.5 0 0 1-.5-.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.5-.5V10h-.5a.499.499 0 0 1-.175-.032l-.179.178a.5.5 0 0 0-.11.168l-2 5a.5.5 0 0 0 .65.65l5-2a.5.5 0 0 0 .168-.11l.178-.178z"/>
</svg>
<svg (click)="delete(item.id)" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash-fill" viewBox="0 0 16 16">
<path d="M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 1 0z"/>
</svg>
</td>
</tr>
</tbody>
</table>
</div>
Now, add the below given CSS to the app.component.css file.
.m-100{
margin: 100px;
}
.main{
padding: 1.5rem;
border: 1px solid #dee2e6;
border-top-left-radius: .25rem;
border-top-right-radius: .25rem;
}
.action svg{
margin: 0px 5px 0px 5px;
}
All these changes will lead to getting the following data.
Source: blog.jscrambler.com
Step 7: Adding New Data
Add the following HTML code in the app.component.html that represents edit/add modal popup.
<button #btnShow style="display: none;" id="btnShow" type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" ></button>
<div id="exampleModal" #myModal class="modal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add New User</h5>
<button #btnClose id="btnClose" type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Name</label>
<input type="text" [(ngModel)]="name" class="form-control" id="exampleFormControlInput1" placeholder="enter name">
</div>
<div class="mb-3">
<label for="exampleFormControlTextarea1" class="form-label">Personal Info</label>
<textarea class="form-control" [(ngModel)]="personalInfo" placeholder="enter some personal info" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" (click)="add()" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Define the personalInfo and name in the app.component.ts. Build a new method known as add which will automatically add up new documents to the userInfo which will be based on the code that you add up.
add(){
this.store.collection('userInfo').add({name : this.name, personalInfo : this.personalInfo});
}
Use ViewChild to add up a reference to the buttons in order to close and open the popups. Define the two methods in order to carry out this activity.
@ViewChild('btnShow')
btnShow!: ElementRef;
@ViewChild('btnClose')
btnClose!: ElementRef;
openDialog(){
this.btnShow.nativeElement.click();
}
closeDialog(){
this.btnClose.nativeElement.click();
}
Now add up the closeDialog method and call in the add method
add(){
this.store.collection('userInfo').add({name : this.name, personalInfo : this.personalInfo});
this.closeDialog();
}
Save all these changes and tap on the add icon in order to add a new record. Add a record in ‘Add New User’ pop-up screen.
Source: blog.jscrambler.com
Deleting Record
To delete a record from Firebase you must call the delete method on the document received with the help of your document ID.
delete(id : string){
this.store.collection('list').doc(id).delete();
}
The delete method is already added to the app.component.html and save the changes to see the result. This Angular and Firebase example will enable you to create an app using both tools.
No comments:
Post a Comment