Skip to main content
Angular Basics
CHAPTER 26 Beginner

Angular with Firebase

Updated: May 18, 2026
5 min read

# CHAPTER 26

Angular with Firebase

1. Chapter Introduction

Firebase is Google's Backend-as-a-Service (BaaS) platform that provides authentication, a real-time NoSQL database (Firestore), cloud functions, and hosting — all without writing a single line of backend code. Combined with Angular, it allows a solo developer or small team to build full-stack, production-ready apps incredibly fast.

2. Learning Objectives

  • Set up a Firebase project and install AngularFire.
  • Implement Firebase Authentication (email/password, Google Sign-In).
  • Perform CRUD operations with Firestore.
  • Deploy an Angular app to Firebase Hosting.
  • Build a Firebase-powered Todo App.

3. Firebase Setup

bash
12
# Install Firebase and AngularFire
npm install firebase @angular/fire
app.config.ts
1234567891011121314151617181920
import { initializeApp, provideFirebaseApp } from '@angular/fire/app';
import { provideAuth, getAuth } from '@angular/fire/auth';
import { provideFirestore, getFirestore } from '@angular/fire/firestore';

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT.firebaseapp.com",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_PROJECT.appspot.com",
  messagingSenderId: "YOUR_ID",
  appId: "YOUR_APP_ID"
};

export const appConfig = {
  providers: [
    provideFirebaseApp(() => initializeApp(firebaseConfig)),
    provideAuth(() => getAuth()),
    provideFirestore(() => getFirestore())
  ]
};

4. Firebase Authentication

auth.service.ts
1234567891011121314151617181920212223242526
import { Injectable } from '@angular/core';
import { Auth, signInWithEmailAndPassword, createUserWithEmailAndPassword,
         signOut, user } from '@angular/fire/auth';
import { Router } from '@angular/router';

@Injectable({ providedIn: 'root' })
export class AuthService {
  currentUser$ = user(this.auth); // Observable of the current user

  constructor(private auth: Auth, private router: Router) {}

  async register(email: string, password: string): Promise<void> {
    await createUserWithEmailAndPassword(this.auth, email, password);
    this.router.navigate([&#039;/dashboard&#039;]);
  }

  async login(email: string, password: string): Promise<void> {
    await signInWithEmailAndPassword(this.auth, email, password);
    this.router.navigate([&#039;/dashboard&#039;]);
  }

  async logout(): Promise<void> {
    await signOut(this.auth);
    this.router.navigate([&#039;/login&#039;]);
  }
}
html
12345
<!-- Display user info using async pipe -->
<ng-container *ngIf="authService.currentUser$ | async as user">
  <p>Logged in as: {{ user.email }}</p>
  <button (click)="authService.logout()">Logout</button>
</ng-container>

5. Firestore CRUD Operations

todo.service.ts
12345678910111213141516171819202122232425262728293031323334353637383940
import { Injectable } from &#039;@angular/core&#039;;
import { Firestore, collection, addDoc, collectionData,
         deleteDoc, doc, updateDoc } from &#039;@angular/fire/firestore&#039;;
import { Observable } from &#039;rxjs&#039;;

export interface Todo {
  id?: string;
  title: string;
  completed: boolean;
  createdAt: Date;
}

@Injectable({ providedIn: &#039;root&#039; })
export class TodoService {
  private todosRef = collection(this.firestore, &#039;todos&#039;);

  constructor(private firestore: Firestore) {}

  getTodos(): Observable<Todo[]> {
    return collectionData(this.todosRef, { idField: &#039;id&#039; }) as Observable<Todo[]>;
  }

  addTodo(title: string): Promise<any> {
    return addDoc(this.todosRef, {
      title,
      completed: false,
      createdAt: new Date()
    });
  }

  deleteTodo(id: string): Promise<void> {
    const todoDoc = doc(this.firestore, `todos/${id}`);
    return deleteDoc(todoDoc);
  }

  toggleComplete(id: string, completed: boolean): Promise<void> {
    const todoDoc = doc(this.firestore, `todos/${id}`);
    return updateDoc(todoDoc, { completed: !completed });
  }
}
todo.component.ts
1234567891011121314
@Component({ selector: &#039;app-todo&#039;, templateUrl: &#039;./todo.component.html&#039; })
export class TodoComponent {
  todos$ = this.todoService.getTodos(); // Real-time Observable!
  newTodo = &#039;&#039;;

  constructor(public todoService: TodoService) {}

  add(): void {
    if (this.newTodo.trim()) {
      this.todoService.addTodo(this.newTodo);
      this.newTodo = &#039;&#039;;
    }
  }
}
html
123456789101112
<input [(ngModel)]="newTodo" placeholder="Add todo..." />
<button (click)="add()">Add</button>

<ul>
  <li *ngFor="let todo of todos$ | async">
    <span [style.textDecoration]="todo.completed ? &#039;line-through' : 'none'">
      {{ todo.title }}
    </span>
    <button (click)="todoService.toggleComplete(todo.id!, todo.completed)">✓</button>
    <button (click)="todoService.deleteTodo(todo.id!)">✕</button>
  </li>
</ul>

6. Firebase Hosting Deployment

bash
1234567891011121314
# Install Firebase CLI
npm install -g firebase-tools

# Login to Firebase
firebase login

# Initialize Firebase in your project
firebase init

# Build the Angular app for production
ng build --configuration=production

# Deploy to Firebase Hosting
firebase deploy

Your app will be live at https://YOURPROJECTID.web.app!

7. Common Mistakes

  • Exposing Firebase config in public repos: The Firebase config IS safe to expose (it's not secret), but always configure Firebase Security Rules in the Firebase Console to restrict who can read/write your database.
  • Not configuring Firestore Security Rules: By default, after 30 days, new Firestore databases require authentication. Always configure rules before going to production.

8. MCQs with Answers

Question 1

What is Firebase?

Question 2

What is the AngularFire library?

Question 3

What type of database is Firestore?

Question 4

What does collectionData() return?

Question 5

What function adds a new document to a Firestore collection?

Question 6

What function deletes a Firestore document?

Question 7

What function partially updates a Firestore document?

Question 8

What CLI tool is used to deploy an Angular app to Firebase Hosting?

Question 9

After running firebase init, what Angular command must you run before firebase deploy?

Question 10

Is the Firebase firebaseConfig object (with apiKey) safe to expose in client-side code?

9. Interview Questions

  • Q: What is the difference between Firebase Authentication and Firestore?
  • Q: How does Firestore's real-time Observable work? How is it different from a standard HTTP GET request?

10. Summary

Firebase dramatically reduces the backend engineering required for common app features. Real-time data synchronization with Firestore, serverless authentication, and one-command deployment to Firebase Hosting make it the perfect backend companion for Angular applications.

11. Next Chapter Recommendation

In Chapter 27: Building REST API Applications, we build a complete CRUD Blog Application that integrates with a traditional REST API backend, implementing GET, POST, PUT, and DELETE operations end-to-end.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·