Part 4 from series: How to build a real-time chat app

Create Angular Components

Display a list of messages with Angular

We will focus on building the user interface to display a list of messages. We will create several standalone components to hold our new feature and focus on presentation.

First we will need to do a bit of wiring up.

Create the Components

Change directory to web-app/src/app from within your project folder.

cd <project-folder-path>/web-app/src/app

Next, we will create several user interface Components that will be responsible for different areas of the page display and interaction to give a good separation of concerns (SoC). This will hopefully make the application easier to understand from just looking at the file system arrangement.

  • CreateMessage that will allow a user to type and send a message.
  • ViewConversation that has the responsibility of displaying an interactive conversation of messages.
  • Messages to tie all components together.

We will use the Angular CLI to generate each component:

ng generate component messages/create-message
ng generate component messages/view-conversation
ng generate component messages/messages

Each command creates a folder inside messages containing a TypeScript class, an HTML template, an SCSS styles file and a spec (unit test) file. All of our components are standalone, which means there are no NgModules to create or declare them in. Instead, each component lists the other components, directives and pipes that its template uses in its own imports array.

If you open the generated messages/messages/messages.ts file, you'll see the component class and its metadata:

File path icon web-app/src/app/messages/messages/messages.ts
import { Component } from '@angular/core';

@Component({
  imports: [],
  selector: 'app-messages',
  styleUrl: './messages.scss',
  templateUrl: './messages.html',
})
export class Messages {}

Notice that the selector is the custom HTML tag we'll use to place this component in a template, and the imports array is empty for now.

Routing

Our application is very simple with regards to routing. There will be just one route to define. Open the file web-app/src/app/app.routes.ts. Routes are defined as an array of objects in this file, which the CLI has already registered with the application for us using provideRouter(routes) in app.config.ts.

To create a route to our messages feature, we need to specify a relative route path and a component to render when a user navigates to the URL route. We will use loadComponent to lazy-load the component, which means the browser only downloads its code when the route is visited. This help with improving core web vitals. Replace the contents of the file with the following:

File path icon web-app/src/app/app.routes.ts
import { Routes } from '@angular/router';

export const routes: Routes = [
  {
    path: '',
    loadComponent: () => import('./messages/messages/messages').then((m) => m.Messages),
  },
];

Within the same directory, our app.html page currently still displays the Angular CLI generated placeholder content. We need to update this to allow routed content to display within a designated area of our page. Replace the contents of this file with the following:

File path icon web-app/src/app/app.html
<router-outlet />

The root App component in app.ts lists RouterOutlet in its imports array from setup, which is needed to use the use the <router-outlet /> selector in its template.

If we run ng serve, we will be able to see the contents from our routed messages/messages/messages.html file.

Building the user interface

Now that we've done all the wiring up, we can now focus on creating the user interface. Open the messages/messages/messages.html file and insert the following code:

File path icon web-app/src/app/messages/messages/messages.html
<div class="messages messages--grid">
  <header class="header">
    Slack Messaging
  </header>
  <div class="messages__conversation">
    <app-view-conversation />
    <app-create-message />
  </div>
</div>

Open the file messages/messages/messages.component.ts and take a look at the @Component metadata near the top of the file.

A component can bind to a HTML template by registering a template or templateUrl property within the @Component metadata. Angular components let us specify a custom HTML tag to allow components to reference each other within their HTML template. This is defined by using a property called selector to associate it with a component.

In our example, the code structure uses a messages class to wrap our entire feature component, a header and a div with class messages__conversation that contains the component selectors app-view-conversation from the view-conversation.ts file and app-create-message from the create-message.ts file that we created earlier.

Before the selectors will work, we have to tell Angular that the Messages component uses them. Open messages/messages/messages.ts, import the two components and add them to the imports array:

File path icon web-app/src/app/messages/messages/messages.ts
import { Component } from '@angular/core';

import { CreateMessage } from '../create-message/create-message';
import { ViewConversation } from '../view-conversation/view-conversation';

@Component({
  selector: 'app-messages',
  imports: [ViewConversation, CreateMessage], // <-- Add the components used in the template
  templateUrl: './messages.html',
  styleUrl: './messages.scss',
})
export class Messages {}

By doing this, we are able to use the selectors to reference our components within the Messages template. If we forget, Angular will tell us at compile time that the element app-view-conversation is not a known element.

If you're curious about the underscore convention used in our HTML classes. This is a common pattern called Block, Element, Modifier (BEM), used for specifying composition relationships within HTML documents and is used throughout this tutorial.

If we check our page in the web-browser, we can see content shown in all our components from using component selectors.

Next we'll add a few styles to lay out the page. Open the file messages/messages/messages.scss and add the following:

File path icon web-app/src/app/messages/messages/messages.scss
.messages--grid {
  display : grid;
  grid-template-columns: 60px 1fr 1fr 1fr 60px;
  grid-template-areas:
    "header   header    header    header    header"
    "content  content   content   content   content";

  @media(min-width: 500px) {
    grid-template-areas:
      ".   header    header    header    ."
      ".   content   content   content   .";
  }

  @media(min-width: 800px) {
    grid-template-columns: 150px 1fr 1fr 1fr 150px;
  }

  .messages__conversation {
    position : relative;
    grid-area: content;
  }
}

.header {
  padding : .5rem;
  grid-area: header;
  font-size : .75rem;
  font-family: 'Helvetica Neue', Arial;
}

This uses CSS grid to centre the conversation in the page, with wider margins on larger screens.

Display the list of messages

To create the user interface for a list of messages, we will need to change a triad of closely related files.

  • A Typescript file to hold all component behaviours and data.
  • An HTML file to describe our component layout with data.
  • An SCSS styles file to define the look and feel for our layout of messages.

The Typescript Component file

The component file (ending in .ts) holds all the behaviours of the components interface. It provisions data in the template using data-binding and handles all events, whether the event is a new message sent back from the server or a users click on a 'send' button.

First we need to define a view-model for our HTML template. This interface will represent the shape of data for a single message that our template expects to bind to. We will put it in a new file that all of our messages components can share. Create the file messages/message.model.ts and add the following code:

File path icon web-app/src/app/messages/message.model.ts
import { Component, OnInit } from '@angular/core';

export interface MessageView {
  id: string;
  sent: Date;
  text: string;
  fromYou: boolean;
  user: {
    name: string;
    colour: string;
    avatarUrl: string;
  };
}

Then open the messages/view-conversation/view-conversation.ts file. We need a property that will hold the actual data of all our messages in an array. Each message object in the array will be structured with the above view-model interface.

We will hold our messages in an Angular signal. A signal is a wrapper around a value that tells Angular when the value changes so that the template updates automatically. We create one with the signal() function and read its current value by calling it like a function, for example messages().

Each message object in the array will be structured with the MessageView view-model interface, which is defined by using a typed array MessageView[].

File path icon web-app/src/app/messages/view-conversation/view-conversation.ts
import { Component, signal } from '@angular/core';

import { MessageView } from '../message.model';

@Component({
  selector: 'app-view-conversation',
  templateUrl: './view-conversation.html',
  styleUrl: './view-conversation.scss',
})
export class ViewConversation {
  // <-- New property to hold messages
  protected readonly messages = signal<MessageView[]>([]);
}

The protected modifier makes the property available to the component's template but not to code outside of the component.

The HTML template file

Next we need to create the markup that we will later use to format the layout of the array of messages held in the component. First we will create a static template but without binding to component data.

Open the messages/view-conversation/view-conversation.html file and replace the contents with the following:

File path icon web-app/src/app/messages/view-conversation/view-conversation.html
<div class="messages-view-conversation">
  <div class="messages-view-conversation__list">
    <div class="messages-view-conversation__item"
      [class.messages-view-conversation__item--you]="false"> <!-- <- Class binding -->

      <span class="messages-view-conversation__time">9:43 AM</span>

      <div class="messages-view-conversation__message-animation"
        [style.border-color]="'#c16fe0'"><!-- <- Style binding -->

        <div class="messages-view-conversation__message">
          <img class="messages-view-conversation__avatar"
            [src]="'https://lh3.googleusercontent.com/a-/AAuE7mAuiepkKGsj-1L9lhHSHtnQsXlVqHEQfJqzOoGz=s96-cc-rg'"
            alt="" /><!-- <- Property binding -->
          <strong class="messages-view-conversation__name">
            Shane Edwards
          </strong><br />
          Hi, how's it going?
        </div>
      </div>
    </div>
  </div>
</div>

Again we've used BEM to structure our HTML. We have an element with class messages-view-conversation, which is a block to surround everything in our component and then various elements within this block denoted with class names prefixed with messages-view-conversation__.

You may have noticed that not all of this template is plain old HTML. We have Angular bindings such as [class.…], [style.…] and [src] within the template that enables the values of each attribute to change when the corresponding properties that they are bound to change from within the Typescript component.

If we open the browser window again at http://localhost:4200, we can see the changes to our UI that show our hard-coded message, avatar and time sent (currently not so exciting, but we have to start somewhere). Lets add some styles to our user interface.

The SCSS styles file

The styles for our component will be written with SCSS (aka SASS), a preprocessor scripting language to compile CSS that helps with maintaining complex stylesheets. The style rules are again formatted with BEM. Class names when compiled will correspond to HTML class names.

Styles are associated with a component by specifying a styleUrl property within a @Component's metadata. This is automatically set up when creating a new component with the Angular CLI. By default, Angular scopes these styles so they only apply to elements in this component's template.

Replace the contents of the file messages/view-conversation/view-conversation.scss with the following:

File path icon web-app/src/app/messages/view-conversation/view-conversation.scss
.messages-view-conversation {
  display : flex;
  flex-direction : column;
  margin : 0;
  padding : .5rem;
  padding-bottom : 0;
  max-height : 400px;
  overflow-y : auto;
  list-style-type : none;
  background-color : #f5f5f5;

  * {
    line-height : 1.4rem;
    box-sizing: border-box;
    font-family: 'Helvetica Neue', Arial;
  }

  h1 {
    font-weight : normal;
  }

  &__heading {
    font-size : 1.8rem;
  }

  &__list {
    position : relative;
  }

  &__item {
    align-self : flex-start;
    margin-left : 5%;
    width : 95%;

    + .messages-view-conversation__item {
      margin-top : 1rem;
    }

    &--you {
      margin-left : 0;
    }
  }

  &__time {
    display : block;
    margin-bottom : .3rem;
    font-size : .8rem;
    color : #666;
  }

  &__message {
    padding : 1rem;
    border-radius : 3px;
  }

  &__message-animation {
    position : relative;
    overflow : hidden;
    border-radius : 3px;
    background-color : #fff;
    border-left : 5px solid #dca629;
  }

  &__message-cover {
    position : absolute;
    top : 0;
    right : 0;
    bottom : 0;
    left : 0;
    opacity: 0;
  }

  &__avatar {
    float : right;
    margin-left : 1rem;
    margin-top : -.4rem;
    margin-right : -.4rem;
  }

  &__name {
    display : inline-block;
    margin-bottom : .2rem;
  }
}

In our new SCSS file we have a top-level Block class selector called .messages-view-conversation, which wraps all other styles within the scope of our component. The Element classes that we wrote in the HTML file are created by prepending the Block name (using &) followed by two underscores and the Element name. Modifiers can be used by prepending the Block name followed by two dashes and the modifier name.

BEM examples with SCSS

The following is an example SCSS block with an element and modifiers.

/* Block */
.block-name {
  font-size : 1.2rem;

  /* Element */
  &__element-name {
    display : inline-block;
    margin-bottom : .2rem;

    /* Optional element modifier */
    &--element-modifier-name {
      color : red;
    }
  }

  /* Optional block modifier */
  &--block-modifier-name {
    border : 1px solid red;
  }
}

When compiled, would create the following CSS rules:

/* Block compiled */
.block-name {
  font-size : 1.2rem;
}

/* Element compiled */
.block-name__element-name {
  display : inline-block;
  margin-bottom : .2rem;
}

/* Element modifier compiled */
.block-name__element-name--element-modifier-name {
  color : red;
}

/* Block modifier compiled */
.block-name--modifier-name {
  border : 1px solid red;
}

Then when we want to use the Block and Element structure in our HTML layout it could look similar to this.

<div class="block-name">
  <div class="block-name__element-name">
    Element of block-name
  </div>
</div>

And when used with optional modifiers.

<div class="block-name block-name--modifier-name">
  <div class="block-name__element-name block-name__element-name--element-modifier-name">
    Element of block-name
  </div>
</div>

Modifiers are useful when you want to create variants of block or element styles such as visually indicating different states of system feedback to a user for things like error or success state.

Go back to your browser window, you should see the messages now with our new styles applied.

Binding the template to component state

In order to make our HTML template display messages from our component (and not just hard-coded within our template file), we need to bind the template to the corresponding state held in the component. Recall that we created a new signal that holds an array of messages on our component in the file view-conversation.ts. We're now going to add some fake message data within this array to help us bind the template to the component.

Open file messages/view-conversation/view-conversation.ts and change the following code from:

File path icon web-app/src/app/messages/view-conversation/view-conversation.ts
export class ViewConversation {
  protected readonly messages = signal<MessageView[]>([]); // <-- Change this
}

to add the following code (no code needs to be deleted):

File path icon web-app/src/app/messages/view-conversation/view-conversation.ts
export class ViewConversation {
  protected readonly messages = signal<MessageView[]>([
    // Include this
    {
      id: '1',
      sent: new Date(),
      text: 'This message is bound to component data',
      user: {
        name: 'Shane Edwards',
        avatarUrl: 'https://lh3.googleusercontent.com/a-/AAuE7mAuiepkKGsj-1L9lhHSHtnQsXlVqHEQfJqzOoGz=s96-cc-rg',
        colour: '0080a2'
      },
      fromYou: false
    },
    {
      id: '2',
      sent: new Date(),
      text: 'Cool',
      user: {
        name: 'You',
        avatarUrl: 'https://avatars.githubusercontent.com/u/5592738?v=4',
        colour: 'c16fe0'
      },
      fromYou: true
    }
  ]);
}

We now have data that we can bind to within our template. Our template is also going to use a date pipe to format the time each message was sent, so we need to import DatePipe and add it to the component's imports array:

File path icon web-app/src/app/messages/view-conversation/view-conversation.ts
import { DatePipe } from '@angular/common'; // <-- Add new import
import { Component, signal } from '@angular/core';

// Existing code...

@Component({
  selector: 'app-view-conversation',
  imports: [DatePipe], // <-- Add new imports property
  templateUrl: './view-conversation.html',
  styleUrl: './view-conversation.scss',
})
export class ViewConversation {
  // Existing code...
}

We now have data that we can bind to within our template. Open file messages/view-conversation/view-conversation.html, we are going to add the bindings by adding the code:

Note: Please take some time to read the annotations in <!-- comments -->.

File path icon web-app/src/app/messages/view-conversation/view-conversation.html
<div class="messages-view-conversation">
  <div class="messages-view-conversation__list">

    <!-- @for block repeating the template for each message in the messages signal -->
    @for (message of messages(); track message.id) {
      <div class="messages-view-conversation__item"
        [class.messages-view-conversation__item--you]="message.fromYou"><!-- Class binding to message.fromYou -->

        <span class="messages-view-conversation__time">
          <!-- Data binding to message.sent with date pipe -->
          {{ message.sent | date: 'shortTime' }}
        </span>

        <div class="messages-view-conversation__message-animation"
          [style.border-color]="'#' + message.user.colour"><!-- Style binding to message.user.colour -->

          <div class="messages-view-conversation__message">
            <img class="messages-view-conversation__avatar"
              [src]="message.user.avatarUrl"
              alt="" /><!-- Property binding to message.user.avatarUrl -->
            <strong class="messages-view-conversation__name">
              <!-- Data binding to message.user.name -->
              {{ message.user.name }}
            </strong><br />

            <!-- Data binding to message.text -->
            {{ message.text }}
          </div>
        </div>
      </div>
    }
  </div>
</div>

There are three ways we bind data from a message within this template.

@for block

The @for control flow block allows us to iterate over an array and copy the contents of the block as many times as there are items in the array.

Inside the @for (...) parentheses, we have message of messages(). What we're doing here is binding to our messages signal in our Typescript component (by calling messages() after of) to get the array to iterate over. This allows each item in the array to be accessed with the message template variable.

The track message.id part is required. It tells Angular how to identify each item, so when the array changes it can add, remove or move only the HTML that needs to, instead of re-creating the whole list.

If you recall, we added two items to our messages array. So our template will be copied two times.

Class and style bindings

We briefly touched on these bindings earlier. A class binding such as [class.new-class-name]="expression" adds or removes a single CSS class depending on whether the expression is a true value. A style binding such as [style.border-color]="expression" sets a single CSS style rule to the value of the expression.

The values in our case are taken from properties on the object held within the message variable, which we can access thanks to the @for block.

For example, the code [class.new-class-name]="message.fromYou" will add the class new-class-name to the element it's attached to when message.fromYou is a true value.

Interpolation

Interpolation allows us to simply embed expressions into HTML to calculate values. This can be used to write or bind data anywhere within our template between markup.

An example of interpolation between markup:

<p>{{ message.interpolatedValue1 }}<br /> {{ message.interpolatedValue2 }}</p>

We also use a date pipe in our template to format a date object into a nice readable text string. Pipes are great for transforming data reactively--given an input they return a predictable output.

If you now go back into your browser, you should see our template bound to the messages component data with two messages displayed.