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

Angular Animations

Techniques for legacy Angular animations

Note: The @angular/animations package has been deprecated since Angular 20.2. It still works in Angular 22 and the following guide is a great way to learn how animations are described step-by-step. Angular's recommended replacement is native CSS withanimate.enter and animate.leave, which you can read about in the animations guide, and the migration guide shows how to convert code like this to it.

Animate new incoming messages in an Angular component

Messages are appearing within our app in real-time from our subscription. Lets make the user interface more interesting with animations.

Our messaging app is already fully working, so if you'd rather skip ahead you can jump straight to the Congratulations section at the end of this page. But if you want some practice developing Angular animations, this step is a good exercise. You will use a trigger, a reusable animation made from a sequence of timed styles and an animation event, and finish by scrolling the page to keep the latest message in view.

There are lots of methods to approaching integration of animations for web documents. We could use SVG animations or add a different set of elements and CSS properties to achieve the same result. This tutorial describes just one method that will work well for our application. It features a responsive web design animation that can adapt to any resolution or display.

Our approach

Our intention is to create a cloned message or spacer element that will act as a placeholder to create the space we need to animate a new incoming message in real time. Once the animation has completed, the spacer will be deleted.

Set up Angular animations

Angular's animation functions live in their own package, which our project doesn't have yet. From your project folder, change directory to web-app and install it, using the same major version as the rest of the Angular packages:

cd <project-folder-path>/web-app
npm install @angular/animations@^22.2.0

Then we need to enable animations for the whole application. Our application is built from standalone components and has no NgModules, so instead of importing a BrowserAnimationsModule, we add a provider to the application config.

Open the file web-app/src/app/app.config.ts and add the following lines defined in comments:

File path icon web-app/src/app/app.config.ts
// Existing imports...
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async'; // <-- Add new import

export const appConfig: ApplicationConfig = {
  providers: [
    // Existing code...
    provideApollo(apolloOptions),
    provideAnimationsAsync(), // <-- Add new provider
  ],
};

The provideAnimationsAsync function enables animations, but waits to load the animation code until it's first needed, which keeps the initial download of our application smaller. If you'd prefer to load it up front, you can use provideAnimations from @angular/platform-browser/animations instead.

Hook up the animation trigger

We're going to add the logic in our component to hook up the animation for new messages before we describe the animation behaviour.

To attach an animation to an HTML element, we first need to describe a trigger to make the association between our template and component animation. In the component metadata add the animations property and new trigger called newMessage:

File path icon web-app/src/app/messages/view-conversation/view-conversation.ts
// Existing code...

@Component({
  selector: 'app-view-conversation',
  imports: [DatePipe],
  templateUrl: './view-conversation.html',
  styleUrl: './view-conversation.scss',
  animations: [ // <-- Add new animation property and trigger
    trigger('newMessage', [

    ])
  ],
})
export class ViewConversation {
  // Existing code...
}

The trigger name will be used in the HTML template to bind to events of the animation. We will later describe the animation inside the trigger.

View-model message properties

We will need to add two optional properties to our existing MessageView interface called spacer and isNew to hold Boolean values. Open the file web-app/src/app/messages/message.model.ts and add them:

File path icon web-app/src/app/messages/message.model.ts
export interface MessageView {
  // Existing code...
  fromYou: boolean;
  spacer?: boolean; // <-- Add new property
  isNew?: boolean; // <-- Add new property
  // Existing code...
}

These will help the template render the animation by defining the state of a new message and also the difference between new and existing messages.

Track which messages are new

Our list of messages is calculated from the data that Apollo holds in its cache, so we need a way to know which messages have just arrived. Since our data service is the one place that every new message passes through (whether it was sent by our mutation or pushed by the subscription), it's the best place to keep track of them.

Open the file web-app/src/app/messages/messages-data.ts and add the following changes:

File path icon web-app/src/app/messages/messages-data.ts
import { Injectable, inject, signal } from '@angular/core'; // <-- Add signal import
// Existing imports...

@Injectable({ providedIn: 'root' })
export class MessagesData {
  private readonly apollo = inject(Apollo);
  private readonly newIds = signal<ReadonlySet<string>>(new Set()); // <-- Add new signal

  /**
   * Messages added since the conversation loaded, which still need to play their entrance animation
   */
  readonly newMessageIds = this.newIds.asReadonly(); // <-- Add new property

  // Existing code...

  messageAnimated(id: string) { // <-- Add new method
    this.newIds.update((ids) => {
      const next = new Set(ids);
      next.delete(id);
      return next;
    });
  }

  private appendMessage(cache: ApolloCache, message: ConversationMessage) {
    // Existing code...

    this.newIds.update((ids) => new Set(ids).add(id)); // <-- Add new line
    cache.writeQuery({ ...query, data: { messages: [message, ...messages] } });
  }
}

The newIds signal holds a Set of the ids of messages that are waiting to finish animating. We add an id just before a message is written to the cache, and messageAnimated removes it again. We always create a new Set instead of changing the existing one, because signals only notify Angular when they're given a different value.

Messages that are loaded when the page opens are never added to this set, so only messages that arrive afterwards will animate.

Create the spacer

We will use the ids to create two new (almost identical) MessageView instances for each new message. One will be a spacer, the other will be the readable message that uses the isNew property set to true for the duration of the animation. Back in the view-conversation.ts file, add a function below our existing toMessageView function and change the messages computed signal to use it:

File path icon web-app/src/app/messages/view-conversation/view-conversation.ts
// Existing code...

function toMessageView(message: ConversationMessage): MessageView {
  // Existing code...
}

/**
 * Add the new function below
 */
function toMessageViews(message: ConversationMessage, newIds: ReadonlySet<string>): MessageView[] {
  const view = toMessageView(message);

  if (!newIds.has(view.id)) {
    return [view];
  }

  return [
    { ...view, isNew: true }, // <-- New property within mixin
    { ...view, spacer: true }, // <-- New spacer instance
  ];
}

@Component({
  // Existing code...
})
export class ViewConversation {
  // Existing code...

  protected readonly messages = computed(() => {
    const result = this.messagesResult();
    const newIds = this.messagesData.newMessageIds(); // <-- Add new line

    if (result?.dataState !== 'complete') {
      return [];
    }

    return (result.data.messages ?? [])
      .filter(isPresent)
      .reverse()
      .flatMap((message) => toMessageViews(message, newIds)); // <-- Change to flatMap
  });
}

A message that isn't new is returned as a single view, exactly as before. A new message is returned as two views, which flatMap flattens into our list of messages. Because our messages signal now reads newMessageIds(), it's recalculated whenever the set of new messages changes.

If you look at our application now (you can open the browser dev tools to explore how the HTML elements interact), you will see two identical messages get created when sending a single message.

We need to turn the additional message into a spacer by attaching existing styles we previously included with a conditional class name to a new element in the template. And adding conditional inline-style rules to the containing messages-view-conversation__item.

Open the HTML layout file view-conversation.html within the same folder and add (or replace with) the following code:

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

  <div class="messages-view-conversation__list">

    <!-- 1. Add the [style.…] bindings below -->
    @for (message of messages(); track message.spacer ? message.id + '-spacer' : message.id) {
      <div class="messages-view-conversation__item"
        [class.messages-view-conversation__item--you]="message.fromYou"
        [style.opacity]="message.spacer ? 0 : 1"
        [style.z-index]="message.spacer ? 0 : 1"
        [style.position]="message.isNew ? 'absolute' : 'static'">

        <span class="messages-view-conversation__time">{{ message.sent | date: 'shortTime' }}</span>

        <!-- 2. Add the [@.disabled] and [@newMessage] bindings below -->
        <div class="messages-view-conversation__message-animation"
          [style.border-color]="'#' + message.user.colour"
          [@.disabled]="!message.isNew"
          [@newMessage]="!message.spacer || ''">

          <!-- 3. Add new cover element -->
          <div class="messages-view-conversation__message-cover cover-anim"
            [style.display]="message.isNew ? 'block' : 'none'"
            [style.background-color]="'#' + message.user.colour"></div>

          <div class="messages-view-conversation__message">
            <!-- Existing code... -->
          </div>
        </div>
      </div>
    }
  </div>
</div>

The new message and its spacer share the same message id, but a track expression for an @for block needs to be unique for each item. So the expression gives the spacer a different key.

Part 1. Add the style bindings

The first part (under comment number 1. above) conditionally adds styles based on whether the message is a spacer or not. The spacer will take up normal document flow to push out the right amount of space for our message so its position is static. This is the reason the spacer also includes the same text as the message so that the size of the space can change with the text, whatever the resolution of the viewport. The spacer is also transparent and stacked underneath the readable message with a z-index and opacity of 0.

Part 2. Add the @.disabled and @newMessage bindings

The second part uses an animation binding @.disabled to conditionally disable the animation unless the message isNew. We want the spacer, and messages that aren't new, to appear immediately.

This part also uses another animation binding to our custom trigger @newMessage that we defined in our component metadata. This syntax will attach our animation to this HTML element only if it's not a spacer. The @ syntax in Angular HTML templates is reserved for describing animation semantics.

Part 3. Add new cover element

In the third part, we add a new element that will display only when the message isNew and not a spacer. This will cover the entire message with a block of colour (the colour defined by Slack data) as it animates and eventually fades to reveal the message underneath. At the moment, the cover has no size to it, which we will adjust later with animations.

When the animation is done

To achieve our animation we create a lot of artifacts that we need to clean up once our animation is complete.

Open the file view-conversation.ts and add the following method after the messages signal.

File path icon web-app/src/app/messages/view-conversation/view-conversation.ts
// Existing code...

export class ViewConversation {
  // Existing code...

  protected readonly messages = computed(() => {
    // Existing code...
  });

  /**
   * Add the new method below
   */
  protected onNewMessageAnimated(id: string) {
    this.messagesData.messageAnimated(id);
  }
}

We only want the additional spacer message to appear for the duration of our animation and remove it once the animation is complete. To remove this we call the messageAnimated method of our data service, which takes the message out of the set of new messages. Our messages signal is then recalculated and no longer creates the spacer. The message that was animated also stops being marked as new, which takes the cover element out of the document flow.

We need to hook up our new onNewMessageAnimated method to be called upon when the animation becomes complete (or done). Back in our HTML template view-conversation.html add the following line beginning with (@newMessage.done)=":

Be sure to move the existing angle bracket > to this next line in order to close the element tag with the new attribute.

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

  <div class="messages-view-conversation__list">
    @for (message of messages(); track message.spacer ? message.id + '-spacer' : message.id) {
      <div class="messages-view-conversation__item"
        [class.messages-view-conversation__item--you]="message.fromYou"
        [style.opacity]="message.spacer ? 0 : 1"
        [style.z-index]="message.spacer ? 0 : 1"
        [style.position]="message.isNew ? 'absolute' : 'static'">

        <span class="messages-view-conversation__time">{{ message.sent | date: 'shortTime' }}</span>

        <!-- Add the (@newMessage.done) event binding below -->
        <div class="messages-view-conversation__message-animation"
          [style.border-color]="'#' + message.user.colour"
          [@.disabled]="!message.isNew"
          [@newMessage]="!message.spacer || ''"
          (@newMessage.done)="message.isNew && onNewMessageAnimated(message.id)"><!-- <-- New event binding -->

          <!-- Existing code... -->
        </div>
      </div>
    }
  </div>
</div>

The above line references the event @newMessage.done, which as you may have guessed calls the function specifed as its value when the newMessage animation completes. The call to onNewMessageAnimated(message.id) from this event is guarded by the isNew property check to make sure this will only fire once for a new message and not for a spacer.

Try some improvements

An improvement to this code would be for the spacer logic to be separated out into its own component. This will demonstrate a clearer separation of concerns and make the code easier to maintain. I leave this optional refactor up to the readers discretion. It would be a good exercise to practice what has been included in this tutorial so far.

Hint: Angular's @if and @switch blocks, or ng-template with ngTemplateOutlet, may offer better points of extension to this area of code.

The Angular animation

We've linked our animation from our template to our component. We're going to separate the logic that describes the animation sequence into its own file. Create and open the file web-app/src/app/messages/new-message.animation.ts.

touch web-app/src/app/messages/new-message.animation.ts

Lets first set up the file with an exported constant for our new animation by adding the following code:

File path icon web-app/src/app/messages/new-message.animation.ts
import { animation, animate, query, sequence, style } from '@angular/animations';

export const newMessageAnimation = animation([

]);

We import a number of functions from the @angular/animations package to build animations. All logic of our animation will be held in the array passed to the animation function.

The array will contain a composition of various instances, these created by calling the other functions we have imported. Creating an animation this way will make the animation reusable in other areas of the application, as described in the reusable animations guide.

Our animation is quite specific and sequential, which will affect what we import from Angular.

In order for the new animation to be used, we need to use it in the animations metadata of the component.

Add the following code to the component metadata in the TypeScript file view-conversation.ts:

File path icon web-app/src/app/messages/view-conversation/view-conversation.ts
// Existing code...
import { newMessageAnimation } from '../new-message.animation'; // <-- Add new import

@Component({
  selector: 'app-view-conversation',
  imports: [DatePipe],
  templateUrl: './view-conversation.html',
  styleUrl: './view-conversation.scss',
  animations: [
    trigger('newMessage', [
      transition(':enter', [ // <-- Add new transition
        useAnimation(newMessageAnimation) // <-- Add reference to newMessageAnimation
      ])
    ])
  ],
})
export class ViewConversation {
  // Existing code...
}

The useAnimation function will link our newly created animation to the transition it is defined in. The call to transition(':enter') will describe what animation to use when the element tagged with newMessage reaches the :enter state.

Transitions

A Transition describes which animation styles to use between each state. We use transition(':enter', [...]) to tell the animation to run upon the element first appearing on (or entering) the page. This transition will run when the @for block updates our list of messages with new content. It will also run in conjunction with state changes to @if blocks.

Open the new-message.animation.ts file, we're going to start animating.

Styles

We first define a style on the host element in our animation. Add the following code to the array passed to the animations function:

File path icon web-app/src/app/messages/new-message.animation.ts
// Existing code...

export const newMessageAnimation = animation([
  style({
    height: 0,
    width: '5px'
  }),
]);

The style rule will immediately run and force a height and width on the host element it is attached to.

Then we will use the query method of the @angular/animations package that is similar to the native DOM method querySelector to find the element with class cover-anim.

File path icon web-app/src/app/messages/new-message.animation.ts
// Existing code...

export const newMessageAnimation = animation([
  style({
    // Existing code...
  }),
  query('.cover-anim', [ // <-- Add new query and style
    style({
      opacity: 1
    })
  ]),
]);

We previously added the cover-anim class to an element in the template. In the animation, we're changing the style of this element to force an opaque opacity again at the very start of the animation. This will be applied to the inner element as soon as the element is drawn on the page.

We then need to add a sequence to describe a sequence of animation timings and styles

File path icon web-app/src/app/messages/new-message.animation.ts
// Existing code...

export const newMessageAnimation = animation([
  style({
    // Existing code...
  }),
  query('.cover-anim', [
    // Existing code...
  ]),
  sequence([ // <-- Add new sequence
    animate('0.15s 400ms ease-out', style({ // <-- Add new animate style
      height: '*',
      width: '5px'
    })),
    animate('0.3s 0ms ease-out', style({ // <-- Add new animate style
      height: '*',
      width: '*'
    })),
  ]),
]);

The new sequence above will animate the host element in two steps. First the height will grow from 0px to full height using * with the width restrained to 5px. This will happen fairly quickly within 0.15 seconds. Only once this has completed will the next animation run. This will release the restriction on the width (using width: '*') to allow the host element to completely fill the area within the next 0.3 seconds.

Lastly we need to fade out the cover element to reveal the message underneath.

File path icon web-app/src/app/messages/new-message.animation.ts
export const newMessageAnimation = animation([
  // Existing code...
  sequence([
    animate('0.15s 400ms ease-out', style({
      // Existing code...
    })),
    animate('0.3s 0ms ease-out', style({
      // Existing code...
    })),
    query('.cover-anim', [ // <-- Add new query
      style({ // <-- Add new style
        opacity: 1
      }),
      sequence([ // <-- Add new sequence
        animate('1s 0ms ease-out', style({
          opacity: 0
        }))
      ])
    ])
  ])
]);

We use query(...) once again to target the element with class cover-anim. The new style call in the array will now target the child element with class cover-anim and not the previous host element to make sure it is opaque. We then declare another sequence to animate the fade of the child element to make it transparent within 1 second.

We should now be able to see our message fully animated. Open http://localhost:4200 and create a new message. Try sending a new message from a downloaded Slack app to see how the animation works with a message sent from another person.

Our animation is working fine but it would be good to stop the text box used to create a message from going out of view every time a new message is created.

Scroll to the latest message

To make our app more interactive, we're going to add automatic scrolling to the latest message as soon as it appears. This will prevent the page jumping around and enable a user to always see the text box they're typing in whilst other users are sending messages to them.

There are two things that can scroll in our application. The list of messages has a maximum height, so it scrolls inside its own box when there are lots of messages. And the page itself can scroll when the screen is small. We will handle both, starting with the list.

Scroll the list of messages

Open the file web-app/src/app/messages/view-conversation/view-conversation.html and add a template reference variable to the outermost element:

File path icon web-app/src/app/messages/view-conversation/view-conversation.html
<div class="messages-view-conversation" #scrollTarget> <!-- <-- Add new identifier #scrollTarget -->
  <!-- Existing code... -->
</div>

Then open the file view-conversation.ts and add the following lines:

File path icon web-app/src/app/messages/view-conversation/view-conversation.ts
import {
  Component,
  ElementRef, // <-- Add new imports
  computed,
  effect,
  inject,
  viewChild,
} from '@angular/core';

// Existing code...

export class ViewConversation {
  private readonly messagesData = inject(MessagesData);
  private readonly scrollTarget = viewChild.required<ElementRef<HTMLElement>>('scrollTarget'); // <-- Add new property

  // Existing code...

  constructor() { // <-- Add new constructor
    effect(() => {
      this.messages();

      setTimeout(() => {
        const el = this.scrollTarget().nativeElement;
        el.scrollTo({ top: el.scrollHeight });
      }, 0);
    });
  }
}

The viewChild function tells Angular to find an element in our template with the template reference variable scrollTarget and gives us a signal holding it. Using viewChild.required means Angular will throw an error if the element can't be found, so we don't need to check for undefined. We read the element by calling the signal, this.scrollTarget(), and the nativeElement property is the actual HTML element.

An effect runs its function again whenever a signal that was read inside it changes. We read this.messages() so that the function runs each time the list of messages changes.

The setTimeout call will ensure the scrolling behaviour happens after the message is rendered. The timeout is set to wait zero milliseconds to run immediately and ensure that scrolling won't happen in the same tick of the event loop. We are already using a spacer to instantly create the room for the animation so we won't have to wait for the full height of the visible message to be rendered before we scroll.

Scroll the page

The scrollable page is controlled by a different component to the message list component that will trigger scrolling. We will have to co-ordinate component interaction via an event binding to add scrolling when a message is added.

Open the file web-app/src/app/messages/messages/messages.html and add the following code:

File path icon web-app/src/app/messages/messages/messages.html
<div class="messages messages--grid" #containerEl> <!-- <-- Add new identifier #containerEl -->
  <header class="header">
    <!-- Existing code -->
  </header>
  <!-- Existing code -->
</div>

Here we're adding another Angular template reference variable called #containerEl to be able to select the element within the component. We can make a reference to the element and save this as a component property.

From the same folder, open the file messages.ts and add the following lines to the top of the class.

File path icon web-app/src/app/messages/messages/messages.ts
import { Component, ElementRef, viewChild } from '@angular/core'; // <-- Add new imports
// Existing imports...

@Component({
  // Existing code...
})
export class Messages {
  private readonly containerEl = viewChild.required<ElementRef<HTMLElement>>('containerEl'); // <-- Add new property

  // Existing code...  
}

Just as before, the viewChild.required function finds the element with the template reference variable containerEl and gives us a signal holding it.

We need to add a method that will do the scrolling to keep the text input element in view when a new message has been added. At the end of the class add the method scrollToContainerBottom:

File path icon web-app/src/app/messages/messages/messages.ts
@Component({
  // Existing code...
})
export class Messages {
  // Existing code...

  protected scrollToContainerBottom() {
    const config: ScrollIntoViewOptions = {
      behavior: 'auto',
      block: 'end',
      inline: 'nearest'
    };

    setTimeout(() => {
      this.containerEl().nativeElement.scrollIntoView(config);
    }, 0);
  }
}

The object is typed as ScrollIntoViewOptions, so TypeScript checks that each value is one the browser accepts. Once more we use setTimeout to make sure the scroll happens after the message has been rendered.

We will call the scrollToContainerBottom method from an output event that will emit from the ViewConversation component. Open the file web-app/src/app/messages/view-conversation/view-conversation.ts and add the following code:

File path icon web-app/src/app/messages/view-conversation/view-conversation.ts
import {
  Component,
  ElementRef,
  computed,
  effect,
  inject,
  output, // <-- Add new import
  viewChild,
} from '@angular/core';
// Existing imports...

@Component({
  // Existing code...
})
export class ViewConversation {
  // Existing code...

  readonly messagesUpdated = output<void>(); // <-- Add new property

  // Existing code...

  constructor() {
    effect(() => {
      this.messages();

      // Existing code...

      this.messagesUpdated.emit(); // <-- Add new line
    });
  }
}

The output function declares an event that a component can send to its parent. We call emit() on it to notify the parent component that the messages have been updated. Because it's inside our effect, this happens each time the list of messages changes.

We can now hook up the event in the template and tell Angular to listen to the messagesUpdated event and call the scrollToContainerBottom method.

Open the file web-app/src/app/messages/messages/messages.html and add the following code to the element app-view-conversation.

File path icon web-app/src/app/messages/messages/messages.html
<div class="messages messages--grid" #containerEl>
  <!-- Existing code... -->
  <div class="messages__conversation">
    <app-view-conversation (messagesUpdated)="scrollToContainerBottom()" /> <!-- <-- Add new event binding -->
    <!-- Existing code... -->
  </div>
</div>

Open your browser at http://localhost:4200 and type a few messages (enough to create a scroll bar down the page) then scroll back to the top of the page. Open a downloaded Slack app, keeping the Angular app in view and type a message in the channel conversation-1.

Once the message has been received in our Angular application, the page should automatically scroll to the bottom showing the latest message animation.

Congratulations!

Well done!🥂🎉 if you've made it all the way to the end. This concludes the final part of the 10 step tutorial on how to build a messaging web application. Below are some links to the source code for your reference.

Angular app on Github Messaging Angular app source code

Angular API on Github Messaging GraphQL api source code