Ionic 7 Firebase List Create, Swipe and Reorder Examples
In the previous tutorial, we talked about how we can create Create, Read, Update and Delete operations in an Ionic app using the Firebase database.
If you want to move one step further, then you must check out How to Create CRUD Operations with Ionic and Firebase.
In this tutorial, we will build a basic Ionic app, then start adding the data in the database, learn how to get that data from Firebase and, most importantly, learn how to display that data in a list view using Ionic lists.
Lists are mostly used GUI elements in mobile applications. Lists are also the best way of displaying multiple information to the user, and a user can easily read the data in a compact space with the help of the list.
We are already familiar with list views, almost all of us view data in a list view on Facebook, Twitter, Tumbler, Instagram and many other social media platforms.
Table of Contents
Create Ionic App
Run the following command to generate a brand new Ionic Angular app.
ionic start ionic-firebase-list blank --type=angular
Enter into the project folder:
cd ionic-firebase-list
Run the below command to add the native core package.
npm install @ionic-native/core --legacy-peer-deps
Disable Strict Type Errors
To avoid TypeScript compiling issues, we just need to open tsconfig.json file:
First, set below property under “compilerOptions” property.
"compilerOptions": {
"strictPropertyInitialization": false,
"skipLibCheck": true
...
}
Secondly, add given props under “angularCompilerOptions”.
"angularCompilerOptions": {
"strictTemplates": false,
...
}
To handle the lists of data in Ionic, we need to create the following pages.
ng generate page edit
ng generate page make
Start the app in the browser:
ionic serve
Setup AngularFirebase Package
Now, to manage the list data we will install AngularFirebase package in an Ionic app. To make the Firebase work with Ionic, we must have a Firebase config key.
Visit console.firebase.google.com and create an account and get the Firebase config keys.
We have written a detailed article on Setting up Firebase with Ionic from Scratch, and you can check out this tutorial to understand how to create an account with Firebase and Get the config keys.
Install AngularFirebase Package
Run below command to install the Firebase library in Ionic and Angular app.
npm install firebase @angular/fire --save
To connect with Firebase database, you need to add the Firebase config keys in environment variable files of your Ionic/Angular app.
Place your keys in environment.prod.ts and environment.ts files:
export const environment = {
production: true,
firebaseConfig: {
apiKey: "<your-api-key>",
authDomain: "<your-auth-domain>",
databaseURL: "<your-database-url>",
projectId: "<your-cloud-firestore-project>",
storageBucket: "<your-storage-bucket>",
messagingSenderId: "<your-sender-id>",
appId: "<your-app-id>",
measurementId: "<your-measurement-id>"
}
};
Next, import and register AngularFireModule, AngularFireDatabaseModule and environment variable in the app.module.ts file.
import { AngularFireModule } from '@angular/fire/compat';
import { AngularFireDatabaseModule } from '@angular/fire/compat/database';
import { environment } from '../environments/environment';
@NgModule({
declarations: [...],
entryComponents: [...],
imports: [
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFireDatabaseModule,
],
providers: [...],
bootstrap: [...]
})
export class AppModule { }
Creating User Service
To manage the data, we will be using a standard service, in which we will define, create, read, update and delete operations. This service will offer us a centralized and reusable code to handle users’ data.
Create folder app/shared then create User.ts file in it and define the data type for User, then, add the following code in User.ts
file.
export class User {
$key: string;
name: string;
email: string
mobile: number;
}
Let’s create shared/user.service.ts file. We will create some methods which will communicate with the Firebase database.
import { Injectable } from '@angular/core';
import { User } from './User';
import {
AngularFireDatabase,
AngularFireList,
AngularFireObject,
} from '@angular/fire/compat/database';
@Injectable({
providedIn: 'root',
})
export class UserService {
userList: AngularFireList<any>;
userRef: AngularFireObject<any>;
constructor(private db: AngularFireDatabase) {}
// Create
createUser(user: User) {
return this.userList.push({
name: user.name,
email: user.email,
mobile: user.mobile,
});
}
// Get single object
getUser(id: string) {
this.userRef = this.db.object('/user/' + id);
return this.userRef;
}
// Get List
getUserList() {
this.userList = this.db.list('/user');
return this.userList;
}
// Update
updateUser(id, user: User) {
return this.userRef.update({
name: user.name,
email: user.email,
mobile: user.mobile,
});
}
// Delete
deleteUser(id: string) {
this.userRef = this.db.object('/user/' + id);
this.userRef.remove();
}
}
Define Routes
To travel between pages, we need to configure the routes, add the below code app-routing.module.ts file:
import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{
path: 'home',
loadChildren: () => import('./home/home.module').then(m => m.HomePageModule)
},
{
path: 'make',
loadChildren: () => import('./make/make.module').then(m => m.MakePageModule)
},
{
path: 'edit/:id',
loadChildren: () => import('./edit/edit.module').then(m => m.EditPageModule)
},
];
@NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
Adding Data to Ionic List
In this step, we will add the data in the Firebase database then by using the UserService’s getUserList()
method we will show the user’s data list in Ionic app.
Create a basic form in Ionic with the help of Angular’s Reactive Forms API, go to make.module.ts and import and register ReactiveFormsModule service in it.
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
ReactiveFormsModule,
FormsModule,
]
})
export class MakeAppointmentPageModule { }
We will use the below logic to add the data in the Ionic 7 list, place the following code in make.page.ts file.
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder } from "@angular/forms";
import { UserService } from '../shared/user.service';
@Component({
selector: 'app-make',
templateUrl: './make.page.html',
styleUrls: ['./make.page.scss'],
})
export class MakePage implements OnInit {
form: FormGroup;
constructor(
private apiService: UserService,
private router: Router,
public fb: FormBuilder
) { }
ngOnInit() {
this.form = this.fb.group({
name: [''],
email: [''],
mobile: ['']
})
}
onFormSubmit() {
if (!this.form.valid) {
return false;
} else {
this.apiService.createUser(this.form.value).then(res => {
this.form.reset();
this.router.navigate(['/home']);
})
.catch(error => console.log(error));
}
}
}
Add the form code in the make.page.html file and start adding the user data in Ionic list.
<ion-header>
<ion-toolbar class="ios hydrated">
<ion-title class="ios title-ios hydrated">Add User</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list lines="full">
<form [formGroup]="form" (ngSubmit)="onFormSubmit()">
<ion-item>
<ion-label position="floating">Name</ion-label>
<ion-input formControlName="name" type="text" required></ion-input>
</ion-item>
<ion-item>
<ion-label position="floating">Email</ion-label>
<ion-input formControlName="email" type="text" required>
</ion-input>
</ion-item>
<ion-item>
<ion-label position="floating">Mobile</ion-label>
<ion-input formControlName="mobile" type="text" required>
</ion-input>
</ion-item>
<ion-row>
<ion-col>
<ion-button type="submit" color="primary" shape="full" expand="block">Create</ion-button>
</ion-col>
</ion-row>
</form>
</ion-list>
</ion-content>
Creating Basic List
Creating a static list in Ionic is very simple, the ion-list component initializes the list. Each list item is wrapped with the ion-item tag.
<ion-list>
<ion-item>
<ion-label>
John Doe
</ion-label>
</ion-item>
</ion-list>
Now, we reached the central part of our tutorial. We will start creating a basic list and populate data dynamically.
Since we are getting data from Firebase database. So first import the service and inject the service in the constructor and make the request to the database using the getUserList() method via UserService.
Add the following code in home.page.ts file.
import { Component, OnInit } from '@angular/core';
import { User } from '../shared/User';
import { UserService } from '../shared/user.service';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
UsersArray = [];
constructor(
private apiService: UserService
) { }
ngOnInit() {
this.fetchBookings();
let bookingRes = this.apiService.getUserList();
bookingRes.snapshotChanges().subscribe(res => {
this.UsersArray = [];
res.forEach(item => {
let a = item.payload.toJSON();
a['$key'] = item.key;
this.UsersArray.push(a as User);
})
})
}
fetchBookings() {
this.apiService.getUserList().valueChanges().subscribe(res => {
console.log('Fetched users list!')
})
}
}
Now, we will dynamically set the list items in our Ionic app. We have created the UsersArray which contains the array of users.
Let’s populate the user’s data in the list dynamically in the home template.
Add the following code in home.page.html file.
<ion-header>
<ion-toolbar>
<ion-title>
Users
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-list-header>
Ionic Lists Example
</ion-list-header>
<ion-item *ngFor="let user of UsersArray">
<ion-label>
<h2>
{{user.name}}
</h2>
<p>
{{user.mobile}}
</p>
</ion-label>
</ion-item>
</ion-list>
</ion-content>
Ionic Basic List Example
Here, *ngFor
directive is iterating over every user item in UsersArray and creating the item by using the ion-item. In the browser, you will se the following result.
Creating List Items Swipeable
Now, we are going to learn how to create a list item swipeable. In list slide panel we will insert the edit and delete buttons. These buttons will update the data from a database.
Edit the app/home/home.page.html file and add the following code.
<ion-list>
<ion-list-header>
Ionic Lists Example
</ion-list-header>
<ion-item-sliding *ngFor="let user of UsersArray">
<ion-item>
<ion-label>
<h2>
{{user.name}}
</h2>
<p>
{{user.mobile}}
</p>
</ion-label>
</ion-item>
<ion-item-options>
<ion-button color="light" [routerLink]="['/edit/', user.$key]">
<ion-icon name="create"></ion-icon>
</ion-button>
<ion-button color="danger" (click)="deleteUser(user.$key)">
<ion-icon name="trash"></ion-icon>
</ion-button>
</ion-item-options>
</ion-item-sliding>
</ion-list>
Let us understand what is going on in the above code. We used ion-item-sliding
tag and run the *ngFor
loop with it. It creates the swipeable panel to display update and delete buttons for every item in a data list.
Following method will delete the item from a data list.
deleteUser(id) {
this.apiService.deleteUser(id)
}
Reordering List Items
To reorder the list, we will use the built-in Reorder component. It is used to drag and drop the list item and It should be used with ion-reorder-group
.
<ion-list>
<ion-reorder-group (ionItemReorder)="reorderList($event)" disabled="false">
<ion-item-sliding *ngFor="let user of UsersArray" reorder="true">
<ion-item>
<ion-label>
<h2>
{{user.name}}
</h2>
<p>
{{user.mobile}}
</p>
</ion-label>
<!-- List reorder button -->
<ion-reorder slot="end" class="ios hydrated"></ion-reorder>
</ion-item>
<ion-item-options>
<ion-button color="light" [routerLink]="['/edit/', user.$key]">
<ion-icon name="create"></ion-icon>
</ion-button>
<ion-button color="danger" (click)="deleteUser(user.$key)">
<ion-icon name="trash"></ion-icon>
</ion-button>
</ion-item-options>
</ion-item-sliding>
</ion-reorder-group>
</ion-list>
Add the following code in the home.page.ts template.
import { Component, OnInit, ViewChild } from '@angular/core';
import { User } from '../shared/User';
import { UserService } from '../shared/user.service';
import { IonReorderGroup } from '@ionic/angular';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
UsersArray = [];
constructor(
private apiService: UserService
) { }
ngOnInit() {
this.fetchBookings();
let bookingRes = this.apiService.getUserList();
bookingRes.snapshotChanges().subscribe(res => {
this.UsersArray = [];
res.forEach(item => {
let a = item.payload.toJSON();
a['$key'] = item.key;
this.UsersArray.push(a as User);
})
})
}
fetchBookings() {
this.apiService.getUserList().valueChanges().subscribe(res => {
console.log('Fetched users list!')
})
}
@ViewChild(IonReorderGroup, { static: true }) reorderGroup: IonReorderGroup;
reorderList(ev: any) {
console.log('Dragged from index', ev.detail.from, 'to', ev.detail.to);
ev.detail.complete();
}
toggleReorderGroup() {
this.reorderGroup.disabled = !this.reorderGroup.disabled;
}
}
Conclusion
Finally, we have completed the Ionic List tutorial, in this tutorial, we learned how to create a regular list and managing the list data with Firebase real-time database.
We also looked at how to create swappable panel in the data list. Along with that we also implemented the list reordering functionality using the Ionic Reorder component.