Angular Firestore CRUD Tutorial/Guide

Firestore

{ Adding Firestore }

ng add @angular/fire

{ src/environments/environment.ts }

Update firebaseConfig with credentials that you get when creating Firebase app.

Forms

{ Adding Forms }

ng add @angular/forms

{ app.module.ts }

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

Interface

You can always populate more definitions to your interface.

ng g i item
export interface Item {
    id?: string;
}

Service

{ Adding service }

ng g s example

{ example.service.ts }

import { Injectable } from '@angular/core';

import {
    Firestore,
    collection,
    doc,
    addDoc,
    getDoc,
    getDocs,
    updateDoc,
    deleteDoc,
} from '@angular/fire/firestore';

import { Item } from './item';

@Injectable({
    providedIn: 'root',
})
export class ExampleService {
    constructor(private firestore: Firestore) {}

    addItem(item: Item): void {
        const ref = collection(this.firestore, 'items');
        addDoc(ref, item);
    }

    async getItem(id: string): Promise<Partial<Item>> {
        const docRef = doc(this.firestore, `items/${id}`);
        const querySnapshot = await getDoc(docRef);
        return { id: querySnapshot.id, ...querySnapshot.data() };
    }

    async getItems(): Promise<Item[]> {
        const colRef = collection(this.firestore, 'items').withConverter(null);
        const querySnapshot = await getDocs(colRef);
        const items = [];

        querySnapshot.forEach((doc) => {
            items.push({ id: doc.id, ...doc.data() });
        });

        return items;
    }

    async updateItem(id: string, data: any): Promise<void> {
        const docRef = doc(this.firestore, `items/${id}`);
        return updateDoc(docRef, data);
    }

    async deleteItem(id: string): Promise<void> {
        const docRef = doc(this.firestore, `items/${id}`);
        return deleteDoc(docRef);
    }
}

Routing

ng add @angular/router

Alterations to { app.module.ts }

import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
    { path: '', component: List },
    { path: 'add', component: AddListComponent },
    { path: 'edit/:id', component: EditListComponent },
];
@NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ] })

Components

Listing items

ng g c list
<table>
    <tbody>
        <tr *ngFor="let item of items;">
            <td>{{ item.id }}</td>
        </tr>
    </tbody>
</table>

Adding items

ng g c add-list

Editing items

ng g c edit-list
Angular Firestore CRUD Guide
Angular Firestore CRUD Guide

Angular Firestore CRUD Guide.


Comments

Only logged in members are able to comment on post.