Master AngularFire2 and Angular by building a CRUD operation app

Follow on LinkedIn

In this article, we are creating a CRUD application with angularFire2 and angular, This module basically provides direct access to the Firebase database, and by using angular and angularFire2, you can create a complete Fullstack application.

Setup Environment

Install Node.js on your machine first, after this, you can install Angular CLI globally using the following command

npm install -g @angular/cli

Create a New angularFire2 and angular App

Now open the terminal and run the below commands to create an angularFire2 and angular project and move inside the created project.

ng new angular-fire-crud-app
cd angular-fire-crud-app

Install AngularFire2

Time to Install AngularFire2 and Firebase by running the following command

npm install firebase @angular/fire

Setup Firebase Project

Visit this link https://firebase.google.com/ and create a Firebase project and get the configuration details from the Firebase console.

Configure AngularFire in Your App

Open the src/environments/environment.ts file and add your Firebase configuration

export const environment = {
  production: false,
  firebaseConfig: {
    apiKey: 'YOUR_API_KEY',
    authDomain: 'YOUR_AUTH_DOMAIN',
    projectId: 'YOUR_PROJECT_ID',
    storageBucket: 'YOUR_STORAGE_BUCKET',
    messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
    appId: 'YOUR_APP_ID'
  }
};

Initialize AngularFire in AppModule

Open the src/app/app.module.ts file and import the necessary modules

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AngularFireModule } from '@angular/fire';
import { AngularFireDatabaseModule } from '@angular/fire/database';
import { environment } from '../environments/environment';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFireDatabaseModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Create Item Model

Create an item.model.ts file in the src/app directory

export interface Item {
  id?: string;
  name: string;
  description: string;
}

Create CRUD Service

Create a crud.service.ts file in the src/app directory

import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireList } from '@angular/fire/database';
import { Item } from './item.model';

@Injectable({
  providedIn: 'root'
})
export class CrudService {
  private itemsRef: AngularFireList<Item>;

  constructor(private db: AngularFireDatabase) {
    this.itemsRef = db.list('/items');
  }

  getItems(): AngularFireList<Item> {
    return this.itemsRef;
  }

  addItem(item: Item): void {
    this.itemsRef.push(item);
  }

  updateItem(key: string, item: Item): void {
    this.itemsRef.update(key, item);
  }

  deleteItem(key: string): void {
    this.itemsRef.remove(key);
  }
}

Create Components

Create components for an item listing, adding, editing, and deleting items using the Angular CLI

ng generate component item-list
ng generate component item-add
ng generate component item-edit
ng generate component item-delete

Implement Components

Modify the components to implement the CRUD functionality using the CrudService:

item-list.component.ts

// Import necessary modules and services

@Component({
  selector: 'app-item-list',
  templateUrl: './item-list.component.html',
  styleUrls: ['./item-list.component.css']
})
export class ItemListComponent implements OnInit {
  items: Item[];

  constructor(private crudService: CrudService) {}

  ngOnInit(): void {
    this.crudService.getItems().valueChanges().subscribe((items: Item[]) => {
      this.items = items;
    });
  }
}

item-add.component.ts

// Import necessary modules and services

@Component({
  selector: 'app-item-add',
  templateUrl: './item-add.component.html',
  styleUrls: ['./item-add.component.css']
})
export class ItemAddComponent {
  newItem: Item = { name: '', description: '' };

  constructor(private crudService: CrudService) {}

  addItem(): void {
    this.crudService.addItem(this.newItem);
    this.newItem = { name: '', description: '' };
  }
}

item-edit.component.ts

// Import necessary modules and services

@Component({
  selector: 'app-item-edit',
  templateUrl: './item-edit.component.html',
  styleUrls: ['./item-edit.component.css']
})
export class ItemEditComponent {
  selectedItem: Item;

  constructor(private crudService: CrudService) {}

  editItem(item: Item): void {
    this.selectedItem = { ...item };
  }

  updateItem(): void {
    this.crudService.updateItem(this.selectedItem.id, this.selectedItem);
    this.selectedItem = null;
  }
}

item-delete.component.ts

// Import necessary modules and services

@Component({
  selector: 'app-item-delete',
  templateUrl: './item-delete.component.html',
  styleUrls: ['./item-delete.component.css']
})
export class ItemDeleteComponent {
  deleteItem(itemKey: string): void {
    this.crudService.deleteItem(itemKey);
  }
}

Create Templates and Styles

Create templates and style files for each component like item-list, item-add, item-edit, and item-delete.

Create Routes

Configure the routes in the src/app/app-routing.module.ts file

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ItemListComponent } from './item-list/item-list.component';
import { ItemAddComponent } from './item-add/item-add.component';
import { ItemEditComponent } from './item-edit/item-edit.component';
import { ItemDeleteComponent } from './item-delete/item-delete.component';

const routes: Routes = [
  { path: '', component: ItemListComponent },
  { path: 'add', component: ItemAddComponent },
  { path: 'edit/:id', component: ItemEditComponent },
  { path: 'delete/:id', component: ItemDeleteComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

Add Routing to App Component

Add the router-outlet directive in the src/app/app.component.html file to display different components based on the route

<router-outlet></router-outlet>

Run the App

Time to start the development server using the following command

ng serve

Now, this link on the browser http://localhost:4200 to see your angularFire2 and angular CRUD app in action!

Feel free to comment. Happy Coding 🙂

Related Posts

1 Comment

Leave a Reply

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

×