Previous page: Integrate GraphQL Subscriptions into Angular components to build a list of messages
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:
// 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:
// 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:
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:
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:
// 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:
<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.
// 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.
<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.