Building a CRUD App with Angular and Firebase

In this tutorial, we will learn how to build a CRUD (Create, Read, Update, Delete) app using Angular and Firebase. Angular is a popular JavaScript framework for building web applications, and Firebase is a powerful backend-as-a-service (BaaS) platform that provides real-time database and authentication services. By combining these two technologies, we can create a fully functional app with a backend database and user authentication.

building crud app angular firebase

Introduction

A CRUD app is an application that allows users to perform four basic operations on data: create, read, update, and delete. These operations are essential for most applications that deal with data management. In this tutorial, we will build a simple CRUD app that allows users to manage a list of tasks.

Angular is a popular framework for building single-page applications (SPAs) and provides many powerful features for developing complex UIs. Firebase, on the other hand, is a cloud-based platform that simplifies the development process by providing backend services such as database and authentication.

Benefits of Angular and Firebase

Angular and Firebase are a great combination for building real-time applications. Angular provides a robust framework for developing complex UIs and managing application state. Firebase, on the other hand, offers a scalable and secure backend infrastructure that can handle real-time data synchronization and authentication.

The benefits of using Angular and Firebase together include:

  • Rapid development: Angular provides a powerful framework for building UIs, and Firebase simplifies the backend development process.
  • Real-time updates: Firebase's real-time database allows data to be synchronized in real-time across multiple clients.
  • Scalability: Firebase provides a scalable infrastructure that can handle a large number of users and data.
  • Authentication: Firebase offers built-in authentication services that can be easily integrated into Angular applications.

Setting Up the Project

Before we begin, we need to set up our development environment. Here are the steps to get started:

Installing Angular CLI

Angular CLI is a command-line interface tool that helps us create and manage Angular projects. To install Angular CLI, open your terminal and run the following command:

npm install -g @angular/cli

Creating a new Angular project

Once Angular CLI is installed, we can use it to create a new Angular project. Run the following command in your terminal:

ng new crud-app

This will create a new directory called "crud-app" with a basic Angular project structure.

Setting up Firebase

To use Firebase in our Angular project, we need to set up a Firebase project and obtain the necessary configuration details. Follow these steps to set up Firebase:

  1. Go to the Firebase website and sign in with your Google account.
  2. Click on "Go to Console" and then click on "Add project".
  3. Give your project a name and click on "Continue".
  4. Enable Google Analytics if you wish, and click on "Continue".
  5. On the "Add Firebase to your web app" screen, click on the "</>" icon to view the configuration details.
  6. Copy the configuration details (apiKey, authDomain, databaseURL, etc.) and save them for later use.

Creating the Database

Before we start building the user interface, let's set up the database structure in Firebase. In this tutorial, we will use the Firebase Realtime Database, which is a NoSQL database that stores data in a JSON-like format.

Defining the data structure

In our CRUD app, we will manage a list of tasks. Each task will have a title and a status (completed or not). We can define the data structure in Firebase as follows:

{
  "tasks": {
    "task1": {
      "title": "Task 1",
      "completed": false
    },
    "task2": {
      "title": "Task 2",
      "completed": true
    },
    ...
  }
}

To set up the database structure, go to the Firebase console, click on "Database" in the left sidebar, and choose the "Realtime Database" option. Click on "Create Database" and choose the "Start in test mode" option for now.

Building the User Interface

Now that we have set up the project and the database, let's start building the user interface for our CRUD app. We will use Angular components to create the different parts of the UI and implement the CRUD operations.

Creating Angular components

Angular components are the building blocks of an Angular application. They encapsulate the HTML, CSS, and JavaScript code required to render a specific part of the UI. In our CRUD app, we will create the following components:

  • TaskListComponent: This component will display the list of tasks.
  • TaskFormComponent: This component will allow users to add or edit tasks.
  • TaskItemComponent: This component will display a single task item.

To create a new component, run the following command in your terminal:

ng generate component task-list

This will generate a new component called TaskListComponent in the src/app/task-list directory. Repeat this process for the other components.

Implementing CRUD operations

Now that we have created the components, let's implement the CRUD operations for managing the tasks. We will use the AngularFire library, which is an Angular-specific library for interacting with Firebase.

To install AngularFire, run the following command in your terminal:

npm install firebase @angular/fire

Once installed, we can import the necessary modules and inject the AngularFire services into our components. Here is an example of how to implement the CRUD operations in the TaskListComponent:

import { Component } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-task-list',
  templateUrl: './task-list.component.html',
  styleUrls: ['./task-list.component.css']
})
export class TaskListComponent {
  tasks$: Observable<any[]>;

  constructor(private db: AngularFireDatabase) {
    this.tasks$ = this.db.list('tasks').valueChanges();
  }

  addTask(title: string) {
    this.db.list('tasks').push({ title, completed: false });
  }

  updateTask(task: any) {
    this.db.object(`tasks/${task.key}`).update(task);
  }

  deleteTask(task: any) {
    this.db.object(`tasks/${task.key}`).remove();
  }
}

In this code snippet, we import the necessary modules and inject the AngularFireDatabase service into our component. We use the valueChanges() method to get an observable of the tasks collection, and the list() and object() methods to perform the CRUD operations.

Authentication and Security

Now that we have implemented the basic CRUD operations, let's add user authentication and secure our Firebase resources. Firebase provides built-in authentication services that allow users to sign up, sign in, and manage their accounts.

Adding user authentication

To add user authentication to our Angular app, we need to install the AngularFireAuth library. Run the following command in your terminal:

npm install @angular/fire firebase

Once installed, we can import the necessary modules and inject the AngularFireAuth service into our components. Here is an example of how to add user authentication in the TaskFormComponent:

import { Component } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';

@Component({
  selector: 'app-task-form',
  templateUrl: './task-form.component.html',
  styleUrls: ['./task-form.component.css']
})
export class TaskFormComponent {
  constructor(private auth: AngularFireAuth) {}

  login(email: string, password: string) {
    this.auth.signInWithEmailAndPassword(email, password);
  }

  logout() {
    this.auth.signOut();
  }
}

In this code snippet, we import the necessary modules and inject the AngularFireAuth service into our component. We use the signInWithEmailAndPassword() and signOut() methods to handle the login and logout functionality.

Securing Firebase resources

To secure our Firebase resources, we need to set up the appropriate security rules. In the Firebase console, go to the "Database" section and click on "Rules". Replace the default rules with the following:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null",
    "tasks": {
      "$task": {
        ".validate": "newData.hasChildren(['title', 'completed']) && newData.child('title').isString() && newData.child('completed').isBoolean()"
      }
    }
  }
}

These rules ensure that only authenticated users can read and write data, and that each task has a valid title and completed status.

Deploying the App

Now that we have built our app, let's deploy it to a production environment. Firebase provides hosting services that allow us to deploy our Angular app with a single command.

Building the production-ready app

To build the production-ready app, run the following command in your terminal:

ng build --prod

This will create a dist/ directory with the compiled and optimized app files.

Deploying to Firebase Hosting

To deploy the app to Firebase Hosting, run the following command in your terminal:

firebase login
firebase init
firebase deploy

The first command logs you into Firebase using your Google account. The second command initializes Firebase for your project and prompts you to select the Firebase features you want to set up. Choose "Hosting" and follow the prompts. The third command deploys your app to Firebase Hosting and gives you a URL where you can access your app.

Conclusion

In this tutorial, we have learned how to build a CRUD app using Angular and Firebase. We started by setting up the project and the Firebase database. Then, we built the user interface using Angular components and implemented the CRUD operations using AngularFire. We added user authentication and secured our Firebase resources. Finally, we deployed the app to Firebase Hosting.

By combining the power of Angular and Firebase, we can build scalable and real-time applications with ease. The ability to synchronize data in real-time and handle user authentication out of the box makes Firebase a great backend choice for Angular developers.