Build a CRUD App with Angular and Firebase

Build a CRUD App with Angular and Firebase

This tutorial shows how to build a basic wiki-style app with Angular and Firebase.

This tutorial shows how to build a basic wiki-style app with Angular and Firebase.

Storage as a Service (SaaS) is becoming ever more popular with many businesses. The advantages are clear. Instead of maintaining your own backend server you can outsource the service to a different provider. This can result in a significant increase in productivity, as well as a reduction in development and maintenance costs. In addition, the worry about server security is offloaded to the storage provider. SaaS is an option whenever the server part of your application can be reduced to storage of object data, optionally with access control. There are a number of different SaaS providers available. Arguably, one of the biggest players in the field is Google with the Firebase service.

In this tutorial, I will be showing you how to create your own Wiki using Angular for the frontend client and Firebase for storing the Wiki documents. You’ll see that it’s easy to create a complete application in minutes.

Set Up the Firebase Database

Firebase offers different methods for storing data. I will be using the new Firestore service instead of the more established Real-time Database. Firestore allows you to set up a more structured database together with a more powerful query API. To get started, open your browser and navigate to the Firebase console at [https://console.firebase.google.com/](https://console.firebase.google.com/ "https://console.firebase.google.com/"). Log in using your Google account and accept all terms and conditions. In the Firebase console, you can see an overview of all your projects.

If you haven’t worked with Firebase before you’ll need to create your first Project. Click on the card with the plus sign that says Add project. In the pop-up that appears you can edit the project name and settings. Change the name to anything you like, accept the terms and conditions, and leave everything else at its default.

When you submit the form you are taken to the Project Overview page. Make a note of the Firebase project URL. You will need it, later on, to set up the client. The first thing that you will have to do here is to create a new database. Select Database in the left sidebar menu. You are given the choice between different technologies for storing your data. I will be using Firestore which allows you to store data in hierarchical format. At the time of writing, the Firestore database is advertised in the large banner at the top of the page. Click Create Database to create a Firestore database.

Another pop-up dialog appears that lets you change the settings of the database. Select Start in test mode to allows any developer to access the database. Click Enable and you will be taken to a dialog that allows you to manually add the first data record to the database. Firestore does not allow a completely empty database so you will have to add some data here.

First, create a new collection called pages. This collection will contain all the wiki pages of your app. Then add a new document consisting of the following fields.

Field Name Type content text created timestamp modified timestamp The first document that you create will be your wiki’s home page. Enter home for the document ID. This is the string that uniquely identifies your page. Then write any text into the content field. I will show you how to integrate markdown into your wiki, so you can enter any markdown string here. Next, enter the current date and time into the created and modified fields. Finally, click Save to save the document. You have now successfully set up your Firebase storage.

Next, you will need to obtain the information for using the service in your application. In the Firebase console click on the gear icon next to Project Overview to open the project settings. In the General tab scroll down to the bottom. You will see a notice telling you that there are no apps in your project. You will not be adding an app here but you can get the information by clicking on the web icon “</>”. A pop-up appears with your API key, database URL etc. Copy the information to a safe place, you will need it later.

Add User Authentication to Your Angular + Firebase App

The client will be implemented with user authentication from Okta. So, before you start writing any client code, you should register your application with Okta. If you don’t have a developer account yet, go on and register for a free account at. Once you have registered, you will be taken to the Okta dashboard. Here you can add a new application that should use Okta authentication by clicking on the Add Application button. The page that appears lets you choose between different types of application. Choose Single Page Application which will take you to the settings page. You need to modify the defaults because Angular uses port 4200 as the default port of its testing server. Your settings should look like this.

Set Up Your Angular Client

The client will be implemented using Angular which is based Node. I will assume that you have installed Node and the npm command on your system. Angular uses a command line client, called ng, to automate many development tasks. If you haven’t done so already, open a terminal and install it globally using npm.

npm install -g @angular/[email protected]


If you are on a system that doesn’t let you modify system files as a normal user, you will have to run this command using sudo. You are now ready to create your application. In the terminal, navigate to a directory of your choice and create the wiki client.

ng new WikiClient --routing --style=css


This will create a directory with the name WikiClient, add some barebones application code in it, and install all necessary packages. Before you make any changes to your code, you can use the Angular schematic provided by Okta to set up authentication. Navigate into the WikiClient directory and run the following command.

ng add @oktadev/schematics


You will be asked about the issuer URL and the client ID of your application. To set them, simply copy and paste the values obtained from the Okta console. The command will add the latest Okta packages for Angular and set up the basic configuration to use Okta authentication in your application.

Add Visual Design to Your Angular + Firebase Application

When implementing responsive front end user interfaces, I really enjoy working with the Zurb Foundation framework. It is a comprehensive set of CSS classes and JavaScript tools that has a huge amount of settings and can be styled according to your needs. For this tutorial, you’ll only be using the CSS part of the framework which can be imported from the CDN. Add the following line into the <head> tag of src/index.html.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/foundation.min.css" integrity="sha256-xpOKVlYXzQ3P03j397+jWFZLMBXLES3IiryeClgU5og= sha384-gP4DhqyoT9b1vaikoHi9XQ8If7UNLO73JFOOlQV1RATrA7D0O7TjJZifac6NwPps sha512-AKwIib1E+xDeXe0tCgbc9uSvPwVYl6Awj7xl0FoaPFostZHOuDQ1abnDNCYtxL/HWEnVOMrFyf91TDgLPi9pNg==" crossorigin="anonymous">


Next, open up src/styles.css and replace the contents with some basic styling.

body {
  margin: 0;
  font-family: sans-serif;
}

h1, h2 {
  text-align: center;
}


You will need to import some modules which you will be using later on and make them available for your application. Open up src/app/app.module.ts and add the following imports to the top of the file.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';


Then add them to the list of imports further down in the same file.

imports: [
  FormsModule,
  ReactiveFormsModule,
  ... ]


The main application design is placed into src/app/app.component.html. Copy the following code into the file.

<div class="top-bar">
  <div class="top-bar-left">
    <button routerLink="/">{{title}}</button>
  </div>
  <div class="top-bar-right">
    <button class="button" *ngIf="!isAuthenticated" (click)="oktaAuth.loginRedirect()"> Login </button>
    <button class="button" *ngIf="isAuthenticated" (click)="oktaAuth.logout()"> Logout </button>
  </div>
</div>
<router-outlet></router-outlet>


The <div class="top-bar"> element defines the application’s toolbar at the top of the page. It contains a link to the wiki’s home page and a button that lets the user log in or out. You will notice the use of the isAuthenticated flag and the oktaAuth property. These have been made available through the application component in src/app/app.component.ts by the Okta schematic that you applied to the client in the previous step. The <router-outlet> is the container in which the router will render its content.

Implement Your Angular + Firebase Wiki

The wiki client will need to connect to the Firebase server. Google provides Node and Angular libraries to interface with the database. As usual, they can be installed with npm.

npm install --save @angular/[email protected] [email protected]


The modules have to be made available to the app. Open src/app/app.module.ts again and add the following imports and configuration.

import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';

const firebaseConfig = {
  apiKey: "<Firebase API key>",
  authDomain: "<Firebase auth domain>",
  databaseURL: "<Firebase database URL>",
  projectId: "<Firebase project ID>",
  storageBucket: "<Firebase storage bucket>",
  messagingSenderId: "<Firebase messaging sender ID>",
};


You can simply paste the information you obtained from the Firebase console into the configuration object. Further down in the same file, add both modules to the imports.

AngularFireModule.initializeApp(firebaseConfig),
AngularFirestoreModule,


You will load the page content into the home page. Open src/app/home/home.component.ts and replace the current content with the following content.

import { Component, OnInit } from '@angular/core';
import { OktaAuthService } from '@okta/okta-angular';
import { ActivatedRoute } from '@angular/router';
import { AngularFirestore } from '@angular/fire/firestore';
import { Subscription } from 'rxjs';
import { DocumentSnapshot } from '@firebase/firestore-types';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  isAuthenticated: boolean;
  slug: string;
  content: string;
  created: number;
  modified: number;

  subs: Subscription;

  constructor(private oktaAuth: OktaAuthService,
              private db: AngularFirestore,
              private route: ActivatedRoute) {
  }

  async ngOnInit() {
    this.route.paramMap.subscribe(params => {
      this.loadPage(params.get('slug') || 'home');
    });

    this.isAuthenticated = await this.oktaAuth.isAuthenticated();
    this.oktaAuth.$authenticationState.subscribe(
      (isAuthenticated: boolean)  => this.isAuthenticated = isAuthenticated
    );
  }

  loadPage(slug) {
    if (this.subs) {
      this.subs.unsubscribe();
    }

    const doc = this.db.collection('pages').doc(slug).get();
    this.subs = doc.subscribe((snapshot) => {
      const page = snapshot.data();
      if (!page) {
        this.content = '### This page does not exist';
        this.slug = undefined;
      } else {
        this.slug = slug;
        this.content = page.content;
        this.created = page.created;
        this.modified = page.modified;
        console.log(page);
      }
    });
  }
}


The HomeComponent loads the page depending on the slug parameter that is passed in through the route. The Firestore API is available through the AngularFirestore injectable. Once loaded, the content, slug and timestamp properties are set from the data obtained. In the home component’s template in src/app/home/home.component.html, then replace the content with the code below.

<div class="grid-container wiki">
  <div class="grid-x">
    <div class="small-12 cell">
      <div class="manage-post" *ngIf="isAuthenticated">
        <button class="button" [routerLink]="['/edit', slug]">Edit</button>
        <button class="button" routerLink="/edit">Create</button>
      </div>
      {{content}}
    </div>
  </div>
</div>


If the user is authenticated, the page also contains a bar with buttons to manage the page. These buttons link to the edit page which you will implement later on in this tutorial. Give this toolbar some style by editing src/app/home/home.component.css.

.manage-post {
  display: flex;
  justify-content: space-between;
  padding: 0.5rem 1rem;
  background-color: #fafafa;
}


The router settings for the home route have to be modified from their default to account for the slug parameter. Open src/app/app-routing.module.ts and modify the routes array.

const routes: Routes = [
  {path: '', redirectTo: '/home/', pathMatch: 'full'},
  {
    path: 'home/:slug',
    component: HomeComponent
  },
  {
    path: 'home',
    component: HomeComponent
  },
  {
    path: 'implicit/callback',
    component: OktaCallbackComponent
  }
];


The application is now ready to show wiki pages from the Firebase server. In the terminal, run ng serve. Then open your browser and navigate to [http://localhost:4200](http://localhost:4200 "http://localhost:4200"). You will see the content of the home page that you entered into the database. However, at this point, the markdown is not rendered correctly. This is quickly remedied. Open the terminal again and install the ngx-markdown package.

npm install --save [email protected]


Again, import the modules at the top of src/app/app.module.ts.

import { MarkdownModule } from 'ngx-markdown';


Then add the MarkdownModule.forRoot() to the imports array of AppModule. Next, make a minor change to src/app/home/home.component.html by changing {{content}} to the following.

<markdown [data]="content"></markdown>


Now, when you look at the wiki’s home page you can see that the markdown is rendered properly.

Edit Pages in Your Angular + Firebase App

Showing wiki pages is not enough for a wiki app. Of course, you will want to create new pages or edit existing ones. Create a new component using the command line tool in the terminal.

ng generate component edit


This will create a number of files in the src/app/edit directory. Open src/app/edit/edit.component.ts and replace its contents with the code below.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AngularFirestore } from '@angular/fire/firestore';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
  editPageForm: FormGroup;
  newPage: boolean = true;
  pending: boolean = true;
  slug: string;

  constructor(private formBuilder: FormBuilder,
              private db: AngularFirestore,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
        this.route.paramMap.subscribe(params => {
      const slug = params.get('slug');
      if (!slug) {
        this.initNewPage();
      } else {
        this.initEditPage(slug);
      }
    });
  }

  initNewPage() {
    this.newPage = true;
    this.pending = false;
    this.editPageForm = this.formBuilder.group({
      slug: ['', Validators.required],
      content: ['', Validators.required]
    });
  }

  initEditPage(slug) {
    const doc = this.db.collection('pages').doc(slug).get();
    const subs = doc.subscribe((snapshot) => {
      const page = snapshot.data();
      if (!page) {
        this.initNewPage();
      } else {
        this.editPageForm = this.formBuilder.group({
          content: [page.content, Validators.required]
        });
        this.newPage = false;
        this.pending = false;
        this.slug = slug;
      }
      subs.unsubscribe();
    });
  }

  savePage() {
    if (!this.editPageForm.valid) return;
    const now = Date.now();
    let slug, document;
    if (this.newPage) {
      slug = this.editPageForm.get('slug').value;
      document = {
        content: this.editPageForm.get('content').value,
        modified: now,
        created: now
      }
    } else {
      slug = this.slug;
      document = {
        content: this.editPageForm.get('content').value,
        modified: now
      }
    }
    this.db.collection('pages').doc(slug).set(document, {merge: true}).then(() => {
      this.router.navigate(['/home', slug]);
    });
  }
}


This component is used to process adding new pages and editing existing ones. Using the Firebase API both operations are performed using the set operation. The {merge: true} option tells Firebase not to delete properties of a document if they are not supplied in the update call. The template for the edit component, in src/app/edit/edit.component.html contains a simple form.

<div class="grid-container wiki">
  <div class="grid-x">
    <div class="small-12 cell">
      <form [formGroup]="editPageForm" (ngSubmit)="savePage()" *ngIf="!pending">
        <label *ngIf="newPage">Slug
          <input type="text" placeholder="Slug" formControlName="slug">
        </label>
        <label>
          Page Content
          <textarea placeholder="Page Content" formControlName="content"></textarea>
        </label>
        <button class="button">Save</button>
      </form>
    </div>
  </div>
</div>


Add a tiny bit of styling in src/app/edit/edit.component.css.

input {
  width: 100%;
}

textarea {
  height: 80vh;
}


To make the edit component available through the router, open src/app/app-routing.module.ts and first, modify the import from okta-angular to include the OktaAuthGuard.

import { OktaCallbackComponent, OktaAuthGuard } from '@okta/okta-angular';


Next, add the import of the EditComponent.

import { EditComponent } from './edit/edit.component';


Then add the following entries to the routes array.

{
  path: 'edit/:slug',
  component: EditComponent,
  canActivate: [OktaAuthGuard]
},
{
  path: 'edit',
  component: EditComponent,
  canActivate: [OktaAuthGuard]
}


Note the canActivate property on these routes. They prevent any user that is not logged in from accessing the page editor. Now you are ready to test your wiki. Open the terminal and run start the Angular test server.

ng serve


Now, open your browser and navigate to [http://localhost:4200](http://localhost:4200 "http://localhost:4200"). If you are not logged into your application, click on the Login link and proceed to enter your username and password. Once logged in, you should see the buttons to add a new page or edit the current one. The data is stored in your Firebase database. This means that you can run your app from anywhere and always access the same pages.

Did you know that it was this easy to create your own Wiki?

Learn More

Build a Basic CRUD App with Node and React

Build a Simple CRUD App with Python, Flask, and React

Build a Basic CRUD App with Laravel and Vue

Build a Simple CRUD App with Spring Boot and Vue.js

Build a Basic CRUD App with Laravel and Angular

Build a Basic CRUD App with Laravel and React

Angular 7 (formerly Angular 2) - The Complete Guide

Learn and Understand AngularJS

The Complete Angular Course: Beginner to Advanced

Angular (Angular 2+) & NodeJS - The MEAN Stack Guide

How to deploy Angular App to Firebase using Angular CLI 8.3+

How to deploy Angular App to Firebase using Angular CLI 8.3+

In this tutorial, we’ll create the production bundles of our Angular application and deploy it to Firebase using Angular CLI 8.3+.

You have finally developed your Angular application and you are ready to deploy it to a hosting provider and show it to the world! But, you think, you still have to do so much work to host the application. Fortunately for you, that's not true any more thanks to the latest 8.3+ version of Angular CLI which added a new command to the Angular developer arsenal, just like the ng add command introduced in Angular 7.

The command is ng deploy and as you can guess, it allows you to deploy your Angular application from the command-line using Angular CLI. The command doesn't work out of the box as you need to use it with the ng add command to install a |CLI builder](https://angular.io/guide/cli-builder) that gives your project the required deployment capability to work with a specific hosting provider. This is quite expected since there are various providers, each one with its own configuration.

In this tutorial, we’ll create the production bundles of our Angular application and deploy it to Firebase using Angular CLI 8.3+.

We assume that you already have initialized a project with Angular CLI and that you have installed or updated your project to the latest version of Angular CLI.

How to automatically deploy your Angular project to Firebase? This can be done in 5 easy steps:

  • Step 0 - Setting up your Firebase account and creating a project
  • Step 1 - Adding the Firebase deployment capability to your Angular project
  • Step 2 - Providing the authorization code to Firebase CLI
  • Step 3 - Selecting a Firebase project
  • Step 4 - Building & deploying your Angular project to Firebase
Step 0 - Setting up your Firebase account and creating a project

In the first step, you need to set up a Firebase account and create a project.

Go to the Getting started page and simply follow the instructions there to set up a Firebase account.

Once you have created a Firebase account, you need to create a project in Firebase's dashboard. Simply click on Add project to create a new project.

A box will show up asking you to provide some information about your project. Provide a name for your project and click on the CREATE PROJECT button.

That's it! You have successfully created a Firebase account and project. Let's now head back to the Angular project.

Step 1 - Adding the Firebase deployment capability to your Angular project

The first step is to navigate to your Angular project and add the deployment capability for your target hosting provider. In our case, it's Firebase.

Go to your terminal, and run the following command from the root of your project:

$ ng add @angular/fire

This will add the Firebase deployment capability to your project.

Step 2 - Providing the authorization code to Firebase CLI

The CLI will ask you to Paste authorization code here:**** and will open your default web browser and ask you to give Firebase CLI permissions to administer your Firebase account:

After you log in with the Google account, you’ll be provided with the authorization code:

Step 3 - Selecting a Firebase project

Next, you’ll be asked: Please select a project: (Use arrow keys or type to search). You should have created a Firebase project before.

The CLI will create the firebase.json and .firebaserc files and update the angular.json file accordingly.

Step 4 - Building & deploying your Angular project to Firebase

Finally, you can deploy your application to Firebase, using the following command:

$ ng deploy

The command will build your application (similarly to the ng deploy --prod command), and send the production assets to Firebase.

Conclusion

Thanks to Angular CLI 8.3+, it's now easier than ever to deploy your Angular project to popular hosting and cloud platforms such as Firebase, GitHub, Now and Netlify. You can also search npm for the required package to target your platform, if one doesn't exist or if you're deploying to a self-managed server, you can either create a builder that allows you to use the ng deploy command or manually deploy your app. Check out the official docs for more information.

How to Use Algolia with Firebase Angular Apps

How to Use Algolia with Firebase Angular Apps

Algolia is a super powerful, scalable API service that allows developers to send different forms of data into their platform and quickly perform search, sort and complex filter queries on top of it.

What is Algolia?

Algolia is a super powerful, scalable API service that allows developers to send different forms of data into their platform and quickly perform search, sort and complex filter queries on top of it. The service is incredibly fast, by using replica indexes to pre-build common query conditions to send your data back as quick as possible.

Why use Algolia with Firebase?

Firebase has come a long way in terms of its accessibility with querying data structures, especially in Firestore. Even with these advancements, it has limitations and often time requires pre-sorted data, using Firebase’s syntax sugar with push ids (push ids contain a date hash in their generation) and sacrificing extra reads/writes and straight forward object structure. Firebase also officially recommends Algolia for performing full-text search operations in Firestore.

Getting Started

In this working example, we will be using Firebase Cloud Functions with triggers to help assist with syncing data changes from Firestore over to Algolia. We will also be using the Algolia Node.JS and JavaScript client module for interacting with their service.

Firebase Cloud Functions

In your functions directory you will need to install the following dependencies to leverage Algolia.

npm install --save algoliasearch @types/algoliasearch

For this example we will listen for whenever a new user document is created, updated or deleted in our custom Firestore collection “users”.

For each of the below examples you will need to replace appId and apiKey with your own access tokens generated through Algolia’s admin panel.

user.onCreate.ts

The userOnCreate trigger is dispatched every time a new document is created in the users collection. In the example below we initialize Algolia with our app’s id and unique API key and initialize the index we want to use in Algolia. Algolia recommends naming your index by the instance/environment you are working with (i.e. dev_, prod_, staging_, next_).

We are also replicating to indexes so that we can sort by the user’s name in either ascending or descending order. Algolia reserves objectID for correlating records in their world; we will use the new document’s path id.

import * as algoliasearch from 'algoliasearch';
import * as functions from 'firebase-functions';

export const userOnCreate = functions.firestore
.document('users/{id}')
.onCreate(async (change, context) => {
const user = change.data();
const client = algoliasearch('appId', 'apiKey');
const index = client.initIndex('dev_users');
await index.setSettings({
replicas: [
'dev_users_name_desc',
'dev_users_name_asc'
]
});
return index.addObject({
objectID: change.id,
...user
});
});

user.onUpdate.ts

The userOnUpdate trigger is very similar to the create trigger. The difference is that we do not need to re-specify the replica indexes since once we register them; they will automatically push data over to the replica indexes any time we write to the parent index (dev_users).

To reduce the operation cost, Algolia allows partial updates to only change specific properties on an index’s object.

import * as algoliasearch from 'algoliasearch';
import * as functions from 'firebase-functions';

export const userOnUpdate = functions.firestore
.document('users/{id}')
.onCreate(async (change, context) => {
const user = change.data();
const client = algoliasearch('appId', 'apiKey');
const index = client.initIndex('dev_users');
return index.partialUpdateObject({
objectID: change.id,
...user
});
});

user.onDelete.ts

The userOnDelete trigger is the simplest operation with an initialize and delete object call to remove the Algolia object by the objectID we defined earlier.

import * as algoliasearch from 'algoliasearch';
import * as functions from 'firebase-functions';

export const userOnDelete = functions.firestore
.document('users/{id}')
.onCreate(async (change, context) => {
const client = algoliasearch('appId', 'apiKey');
const index = client.initIndex('dev_users');
return index.deleteObject(change.id);
});

Export all of these constants to your root index.ts file. This will register them as new Firebase Cloud Functions when you build and deploy. At this point any time you change documents in Firestore (either directly through the Firebase Console or with your app) it will trigger these functions to push and sync data across to Algolia.

firebase deploy --only functions:userOnCreate,functions:userOnUpdate,functions:userOnDelete
Application Side
You can store Algolia’s search-only access token (this is different than the apiKey used in Cloud Functions) in your environments file to easily access/import it.

Create a simple service to easily interact with your Algolia indexes.

user.service.ts

import * as algoliasearch from 'algoliasearch';

@Injectable()
export class UserService {

client: algoliasearch.Client;

init(config: {
appId: string,
apiKey: string
}) {
this.client = algoliasearch('appId', 'apiKey');
}

fetchUsers(options: algoliasearch.QueryParameters) {
const userSearch = this.client.initIndex('dev_users');
return userSearch.search(options);
}

fetchUsersByNameAsc(options: algoliasearch.QueryParameters) {
const userSearch = this.client.initIndex('dev_users_name_asc');
return userSearch.search(options);
}

fetchUsersByNameDesc(options: algoliasearch.QueryParameters) {
const userSearch = this.client.initIndex('dev_users_name_desc');
return userSearch.search(options);
}

}

In your component, provide UserService and make the following method calls to test the response back from Algolia.

async ngOnInit() {
this.init({ appId: 'foo', apiKey: 'bar' });
const res = await this.fetchUsers({
page: 0,
length: 10,
query: 'Sean'
});
console.log('res', res);
}

This method call will attempt to load the first page of results, up to 10 records that has a searchable attribute that matches “Sean”.

Final Thoughts

Without getting too far into the weeds of Algolia’s client and explicitly focusing on syncing data over and quickly logging that information out; we can see that Algolia serves as a powerful interface to receive the exact data we need.

In our implementation on Hive, we use Algolia to handle paginated admin tables, infinite scroll experiences, pre-filtering collection records by specific conditions and sorting table data. You can also leverage Algolia as a read-only database, only storing/syncing documents that the client should have access to. This is powerful when using concepts such as soft deletes, where you stamp a document with a deletedAt timestamp in Firestore and remove the object from Algolia. By doing this, you can always recover the document back, but all querying logic from Algolia will treat the document as being deleted.

Thanks for reading. If you liked this post, share it with all of your programming buddies!

Further reading

☞ Learn and Understand AngularJS

☞ The Complete Angular Course: Beginner to Advanced

☞ Angular Crash Course for Busy Developers


Originally published on medium.com

Build a CRUD App with Angular 8 and Firebase

Build a CRUD App with Angular 8 and Firebase

This Angular 8/9 tutorial explains how to use Angular 8/9 with Firebase and Firestore to create an app that implements the common CRUD operations. How to add Firebase CRUD operations to your Angular 8 project that allow you to create, read, update and delete data from a Firestore database. How to set up Firebase in our Angular 8 project, and create a service for implementing Firebase CRUD operations using the Firestore realtime database.

In this tutorial, you'll be using Angular 8/9 with Firebase and Firestore to create an app that implements the common CRUD operations.

We'll see setp by step how to set up Firebase in our Angular 8 project, and create a service for implementing Firebase CRUD operations using the Firestore realtime database.

These are the steps of our Angular Firebase CRUD tutorial:

  • Step 1 - Creating your Angular 8 Project
  • Step 2 - Creating a Firebase Project and a Firestore Database
  • Step 3 - Installing and Adding Firebase to your Angular 8 Project.
  • Step 4 - Create an Angular 8 Model
  • Step 5 - Creating an Angular 8 Service
  • Step 6 - Creating a Component for Making CRUD Operations
What is CRUD?

CRUD stands for Create, Read, Update and Delete and refer to the operations that we run against a database to createn retrieve and update data. In this example, the database is a Firestore database that exists on the cloud.

Note: This tutorial works with Angular 9.

Prerequisites

Before starting this tutorial, you first need to make sure, you have:

  • A recent version of Node.js (v10+) and NPM installed on your system,
  • The latest Angular CLI 8 installed on your system.

If you have the prerequisites, you are ready to start creating your project!

Step 1 - Creating your Angular 8 Project

The first step in this tutorial is creating a new Angular 8 project using the CLI.

Head over to your terminal and run the following command:

$ ng new angular-firebase-crud

The CLI will ask if you want to add routing to your project (you can choose any option you want) and which style sheet format you want to use (You can select CSS).

After that, your project files will be generated and your project's dependencies will be installed.

Step 2 - Creating a Firebase Project and a Firestore Database

Now that your project is generated, you need to proceed with creating a Firebase project and a Firestore database. For this matter, you simply need to go to the Firebase Console and create a new Firebase project.

Next head to the Project Overview >Develop >Database page and create a new Firestore database. For now, make sure you enable test mode so you don't need any permissions to access the database.

Step 3 - Installing and Adding Firebase to your Angular 8 Project.

After creating your Firebase project and your Firestore database you next need to install the firebase and @angular/fire packages as follows:

$ cd ./angular-firebase-crud
$ npm install --save firebase @angular/fire

Next go to your Firebase project overview then click on web and copy the config data.

Next, open the environments/environment.ts file in your Angular 8 project and add the firebaseConfig object inside the environment object.

export const environment = {
  production: false,
  firebaseConfig : {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    databaseURL: "YOUR_DATABASE_URL",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID"
  }
};

Finally, you have to set up Firebase in your project. Open the src/app/app.module.ts file and update it accordingly:

import { AngularFireModule } from '@angular/fire';
import { AngularFireDatabaseModule } from '@angular/fire/database';
import { environment } from '../environments/environment';

@NgModule({
        // [...]
    imports: [
        // [...]
        AngularFireModule.initializeApp(environment.firebaseConfig),
        AngularFireDatabaseModule
    ],

You simply import AngularFireModule and AngularFireDatabaseModule and you add them to the imports array of the main application module.

You also call the initializeApp() method of AngularFireModule to pass the configuration object that you added earlier to the environments/environment.ts file.

That's it, you now have added Firebase and Firestore to your Angular 8 project.

Step 4 - Create an Angular 8 Model

After setting up Firestore in your project, you can proceed with creating a model class. In the simple example, we suppose that you are creating an insurance app where we need to manage a set of policies.

An insurance application will often contain more that one type of data like clients, employees and policies etc. In this example, we'll just focus on the policy entity.

Let's create a model for our insurance policy entity as follows:

$ ng g class policy --type=model

Next, open the src/policy.model.ts file and update it as follows:

export class Policy {
    id: string;
    policyNumber: string;
    creationDate: Date;
    effectiveDate: Date;
    expireDate: Date;
    paymentOption: string;
    policyAmount: number;
    extraInfo: string;
}

This is an example of an insurance policy with many fields and relationships with other entities omitted for the sake of simplicity.

Step 5 - Creating an Angular 8 Service

An Angular service allows you to encapsulate the code that could be repeated in many places in your project. Using the Angular CLI, run the following command to generate a service:

$ ng g service policy

Next, open the src/policy.service.ts file and update it accordingly.

First, import AngularFirestore and the Policy model as follows:

import { AngularFirestore } from '@angular/fire/firestore';
import { Policy } from 'src/app/policy.model';

Next, inject AngularFirestore in your service via its constructor:

export class PolicyService {
  constructor(private firestore: AngularFirestore) { }
}

Next, add the getPolicies() method to retrieve the available policies from the Firestore collection:

getPolicies() {
    return this.firestore.collection('policies').snapshotChanges();
}

You also need to add the createPolicy() method to persist an insurance policy in the Firestore database:

createPolicy(policy: Policy){
    return this.firestore.collection('policies').add(policy);
}

Next, you need to add the updatePolicy() method to update an insurance policy by its identifier:

updatePolicy(policy: Policy){
    delete policy.id;
    this.firestore.doc('policies/' + policy.id).update(policy);
}

Finally, you can add the deletePolicy() method to delete an insurance policy by its identifier:

deletePolicy(policyId: string){
    this.firestore.doc('policies/' + policyId).delete();
}

Step 6 - Creating a Component for Making CRUD Operations

After creating the model and service for creating, reading, updating and deleting insurance policies, you now need to create the component for testing our methods:

Using Angular CLI 8 run the following command to generate a component:

$ ng g c policy-list

Now, open the src/app/policy-list/policy-list.component.ts file and update it accordingly:

import { Component, OnInit } from '@angular/core';
import { PolicyService } from 'src/app/policy.service';
import { Policy } from 'src/app/policy.model';

@Component({
  selector: 'policy-list',
  templateUrl: './policy-list.component.html',
  styleUrls: ['./policy-list.component.css']
})
export class PolicyListComponent implements OnInit {

  policies: Policy[];
  constructor(private policyService: PolicyService) { }

  ngOnInit() {
    this.policyService.getPolicies().subscribe(data => {
      this.policies = data.map(e => {
        return {
          id: e.payload.doc.id,
          ...e.payload.doc.data()
        } as Policy;
      })
    });
  }

  create(policy: Policy){
      this.policyService.createPolicy(policy);
  }

  update(policy: Policy) {
    this.policyService.updatePolicy(policy);
  }

  delete(id: string) {
    this.policyService.deletePolicy(id);
  }
}

Updating the Component Template

Now let's update the component's template to display the insurance policies and also display buttons that can be used to create, update and delete policies:

Open the src/app/policy-list.component.html file and add the following HTML markup:

<table>
  <thead>
    <th>Number</th>
    <th>Created At</th>
    <th>Expire At</th>
    <th>Amount</th>
  </thead>
  <tbody>
    <tr *ngFor="let policy of policies">

      <td>{{policy.policyNumber}}</td>
      <td>{{policy.creationDate}}</td>
      <td>{{policy.expireDate}}</td>
      <td>{{policy.policyAmount}}</td>
      <td>
          <button (click)="delete(policy.id)">Delete</button>
      </td>
    </tr>
  </tbody>
</table>

Below the <table> markup, you can also add a form to create an insurance policy.

Conclusion

In this tutorial, we've seen by example how to add Firebase CRUD operations to your Angular 8 project that allow you to create, read, update and delete data from a Firestore database.