How to Create a Chat App with Angular

4 min read
Ayooluwa I.
Ayooluwa I.
Published February 28, 2020 Updated February 18, 2022

💡 There’s a newer version of this tutorial! Stream now offers a dedicated Angular Chat SDK, paired with a new official Angular Chat App Tutorial.

The new SDK drastically simplifies the development process described below. You can still skim this post for inspiration, but please refer to the new resources linked above for consistently up-to-date information on developing in-app messaging with Angular.

In this tutorial, I’ll take you through building a live chat application with Angular 9 and Stream Chat. I’ll demonstrate how to work with channels and how to send messages in real-time between users. In addition, you’ll see how to keep track of the number of channels that a user belongs to, and also how to retrieve the message history for a channel.

Here’s how the final messaging application will function:

Simple Real Time Live Chat Example App

Prerequisites

Before you continue on with this tutorial, make sure you have Node.js and npm installed. You also need to have installed the Angular CLI package. If you’ve already installed it, make sure you update to the latest version:

$ npm install -g @angular/cli

Signing Up for Stream

Create a free Stream account or sign in to your existing account. Once you’re logged in, create a new application and grab your app access keys, which we’ll be making use of shortly:

Bootstrapping the Angular App

Run the command below to create a new Angular app with Angular CLI. When prompted to add Angular routing, hit N, and choose CSS as the preferred stylesheet format.

$ ng new chatroom && cd chatroom

Next, install the additional dependencies we’ll be making use of:

$ npm install express cors dotenv body-parser stream-chat axios @types/node

The @types/node package is necessary to provide "type" definitions for Node.js. Update your tsconfig.app.json file to include the "node" "types" definitions as shown below:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": ["node"]
  },
  "files": ["src/main.ts", "src/polyfills.ts"],
  "include": ["src/**/*.ts"],
  "exclude": ["src/test.ts", "src/**/*.spec.ts"]
}

At this point, you can run ng serve to start the development server. Open http://localhost:4200 in your browser to view the running application.

Setting Up the Server

Create a new server.js file in your project directory and populate it with the following code:

require('dotenv').config();

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const { StreamChat } = require('stream-chat');

const app = express();

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// initialize Stream Chat SDK

Our server contains only one route (/join), which expects a username to be included in the request body. When this happens, an authentication token is generated for the user who will be created on the chat instance (or updated if the user already exists). By default, user tokens are valid indefinitely; you can set an expiration on a token by passing the number of seconds till expiration as the second parameter.

After this, the user is added to a channel of the team type whose ID is set to talkshop and the generated token is sent back to the client to enable user authentication on the frontend. You can learn more about channel types here, including how to create your own, if the defaults don’t work for you.

We need to set up some environmental variables before we can start the server. Create a new .env file in your project root and paste in your Stream credentials, as shown below:

PORT=5500
STREAM_API_KEY=
STREAM_APP_SECRET=

Now, go ahead and start your server by running node server.js to make it available on PORT 5500.

Building the Chat Interface

Let’s create the HTML template and styles for the application. Open up src/app/app.component.html in your text editor and change it to look like this:

<link
  rel="stylesheet"
  href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
  integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
  crossorigin="anonymous"
/>
<link
  href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css"
  type="text/css"
  rel="stylesheet"
/>

<!-- Toolbar -->
<div class="content" role="main">
  <div *ngIf="!channel" class="login">

Next, add the styles for the app to src/app/app.component.css:

.login {
	position: absolute;
	width: 100%;
	max-width: 600px;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
}

.container {
	max-width: 1170px;
	margin: auto;
}

img {

Now, we can go ahead and write the logic for the application. Locate app.module.ts and import FormsModule which exports the required providers and directives for template-driven forms and makes them available in our AppComponent:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, FormsModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

Finally, update your app.component.ts file as shown below:

import { Component } from '@angular/core';
import { StreamChat, ChannelData, Message, User } from 'stream-chat';
import axios from 'axios';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  title = 'angular-chat';
  channel: ChannelData;
  username = '';
  messages: Message[] = [];
  newMessage = '';

At this point, a login form should be rendered on the page. It only contains a "username" field, which is enough to demonstrate how the app works, although you’d have a proper authentication flow in a real application.

Once the form is submitted, the joinChat() method is called, which submits the username to the /join route that we set up earlier, and receives a token from the server, which is subsequently used to set the current user.

After this, we connect to the talkshop channel, and listen for new messages on the channel, thanks to Stream’s event capabilities. This allows us to update the UI whenever a new message is sent to the channel. We do this by appending the new message to the messages array, so that the new message is displayed in the chat window.

To render the list of channels that a user belongs to on the sidebar, we use the queryChannels() method, which is documented here. It accepts query filters, which you can use on any of the built-in channel fields or any custom ones you may have defined.

New messages are sent to the room by submitting the form at the bottom of the chat window according to the code in sendMessage(). The text input is immediately cleared by setting this.newMessage to an empty string.

To test the application, open it in separate tabs and login using different usernames. Send a few messages using each user:

Example real-time chat app built with Angular 9 and Stream components

Final thoughts

That concludes this tutorial on how to build a real-time chat application in Angular!

You can now build on the knowledge gained here to create a live chatting solution that solves a real-world messaging problem. You can check out other things Stream Chat can do by viewing its extensive documentation. The complete code for this tutorial can be found in the GitHub repository.

Thanks for reading, and happy coding!

decorative lines
Integrating Video With Your App?
We've built an audio and video solution just for you. Launch in days with our new APIs & SDKs!
Check out the BETA!