Implementing a Multi-user Chat Room with Angular and Firebase

Creating a multi-user chat room is a popular project for developers looking to build real-time communication features. Using Angular for the frontend and Firebase for backend services makes this process straightforward and scalable. This guide outlines the key steps to implement such a chat room.

Setting Up Firebase

First, create a Firebase project in the Firebase Console. Enable the Firestore database to store chat messages and set up authentication if you want user login features. Firebase provides real-time updates, which are essential for a live chat experience.

Configuring Angular Project

Start by creating a new Angular project using Angular CLI:

ng new chat-room

Install Firebase and AngularFire packages:

npm install firebase @angular/fire

Connecting Angular with Firebase

Import AngularFire modules in your app module and initialize Firebase with your project credentials:

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

@NgModule({
  imports: [
    AngularFireModule.initializeApp(environment.firebaseConfig),
    // other imports
  ],
  // other configurations
})
export class AppModule { }

Creating the Chat Service

Develop a service to handle message sending and receiving:

import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';

@Injectable({ providedIn: 'root' })
export class ChatService {
  constructor(private firestore: AngularFirestore) { }

  getMessages() {
    return this.firestore.collection('messages', ref => ref.orderBy('timestamp')).snapshotChanges();
  }

  sendMessage(message: string, user: string) {
    return this.firestore.collection('messages').add({
      text: message,
      user: user,
      timestamp: new Date()
    });
  }
}

Building the Chat Component

Create a component to display messages and input form:

import { Component, OnInit } from '@angular/core';
import { ChatService } from '../services/chat.service';

@Component({
  selector: 'app-chat',
  templateUrl: './chat.component.html'
})
export class ChatComponent implements OnInit {
  messages: any[] = [];
  newMessage: string = '';
  userName: string = 'Anonymous';

  constructor(private chatService: ChatService) { }

  ngOnInit() {
    this.chatService.getMessages().subscribe(data => {
      this.messages = data.map(e => {
        return {
          id: e.payload.doc.id,
          ...e.payload.doc.data()
        };
      });
    });
  }

  send() {
    if (this.newMessage.trim()) {
      this.chatService.sendMessage(this.newMessage, this.userName);
      this.newMessage = '';
    }
  }
}

And the HTML template:

<div class="chat-window">
  <div *ngFor="let msg of messages" class="message">
    <strong>{{msg.user}}:</strong> {{msg.text}}<br>
    <small>{{msg.timestamp?.toDate() | date:'shortTime'}}</small>
  </div>
</div>
<div class="input-area">
  <input [(ngModel)]="newMessage" placeholder="Type a message..." />
  <button (click)="send()">Send</button>
</div>

Conclusion

By integrating Angular with Firebase, you can create a fully functional multi-user chat room with real-time updates. This setup is scalable and adaptable, allowing further enhancements like user authentication, message notifications, and more.