Animate multiple elements using query() and stagger() functions
Parallel animation using group() function
Sequential vs. parallel animations
Filter animation example
Animating the items of a reordering list
Animations and Component View Encapsulation
Animation sequence summary
More on Angular animations
Prerequisites
link
A basic understanding of the following concepts:
Introduction to Angular animations
Transition and triggers
So far, we've learned simple animations of single HTML elements.
Angular also lets you animate coordinated sequences, such as an entire grid or list of elements as they enter and leave a page.
You can choose to run multiple animations in parallel, or run discrete animations sequentially, one following another.
The functions that control complex animation sequences are:
Functions
Details
query()
Finds one or more inner HTML elements.
stagger()
Applies a cascading delay to animations for multiple elements.
group()
Runs multiple animation steps in parallel.
sequence()
Runs animation steps one after another.
The query() function
link
Most complex animations rely on the
query()
function to find child elements and apply animations to them, basic examples of such are:
Examples
Details
query()
followed by
animate()
Used to query simple HTML elements and directly apply animations to them.
query()
followed by
animateChild()
Used to query child elements, which themselves have animations metadata applied to them and trigger such animation (which would be otherwise be blocked by the current/parent element's animation).
The first argument of
query()
is a css selector string which can also contain the following Angular-specific tokens:
Tokens
Details
:enter
:leave
For entering/leaving elements.
:animating
For elements currently animating.
@*
@triggerName
For elements with any—or a specific—trigger.
:self
The animating element itself.
Entering and Leaving Elements
Not all child elements are actually considered as entering/leaving; this can, at times, be counterintuitive and confusing. Please see the query api docs for more information.
You can also see an illustration of this in the animations live example (introduced in the animations introduction section) under the Querying tab.
Animate multiple elements using query() and stagger() functions
link
After having queried child elements via
query()
, the
stagger()
function lets you define a timing gap between each queried item that is animated and thus animates elements with a delay between them.
The following example demonstrates how to use the
query()
and
stagger()
functions to animate a list (of heroes) adding each in sequence, with a slight delay, from top to bottom.
Use
query()
to look for an element entering the page that meets certain criteria
For each of these elements, use
style()
to set the same initial style for the element.
Make it transparent and use
transform
to move it out of position so that it can slide into place.
Use
stagger()
to delay each animation by 30 milliseconds
Animate each element on screen for 0.5 seconds using a custom-defined easing curve, simultaneously fading it in and un-transforming it
You've seen how to add a delay between each successive animation.
But you might also want to configure animations that happen in parallel.
For example, you might want to animate two CSS properties of the same element but use a different
easing
function for each one.
For this, you can use the animation
group()
function.
NOTE
:
The
group()
function is used to group animation
steps
, rather than animated elements.
The following example uses
group()
s on both
:enter
and
:leave
for two different timing configurations, thus applying two independent animations to the same element in parallel.
Complex animations can have many things happening at once.
But what if you want to create an animation involving several animations happening one after the other? Earlier you used
group()
to run multiple animations all at the same time, in parallel.
A second function called
sequence()
lets you run those same animations one after the other.
Within
sequence()
, the animation steps consist of either
style()
or
animate()
function calls.
Use
style()
to apply the provided styling data immediately.
Use
animate()
to apply styling data over a given time interval.
Filter animation example
link
Take a look at another animation on the live example page.
Under the Filter/Stagger tab, enter some text into the
Search Heroes
text box, such as
Magnet
or
tornado
.
The filter works in real time as you type.
Elements leave the page as you type each new letter and the filter gets progressively stricter.
The heroes list gradually re-enters the page as you delete each letter in the filter box.
The HTML template contains a trigger called
filterAnimation
.
The code in this example performs the following tasks:
Skips animations when the user first opens or navigates to this page (the filter animation narrows what is already there, so it only works on elements that already exist in the DOM)
Filters heroes based on the search input's value
For each change:
Hides an element leaving the DOM by setting its opacity and width to 0
Animates an element entering the DOM over 300 milliseconds.
During the animation, the element assumes its default width and opacity.
If there are multiple elements entering or leaving the DOM, staggers each animation starting at the top of the page, with a 50-millisecond delay between each element
Animating the items of a reordering list
link
Although Angular animates correctly
*ngFor
list items out of the box, it will not be able to do so if their ordering changes.
This is because it will lose track of which element is which, resulting in broken animations.
The only way to help Angular keep track of such elements is by assigning a
TrackByFunction
to the
NgForOf
directive.
This makes sure that Angular always knows which element is which, thus allowing it to apply the correct animations to the correct elements all the time.
IMPORTANT
:
If you need to animate the items of an
*ngFor
list and there is a possibility that the order of such items will change during runtime, always use a
TrackByFunction
.
Animations and Component View Encapsulation
link
Angular animations are based on the components DOM structure and do not directly take View Encapsulation into account, this means that components using
ViewEncapsulation.Emulated
behave exactly as if they were using
ViewEncapsulation.None
(
ViewEncapsulation.ShadowDom
behaves differently as we'll discuss shortly).
For example if the
query()
function (which you'll see more of in the rest of the Animations guide) were to be applied at the top of a tree of components using the emulated view encapsulation, such query would be able to identify (and thus animate) DOM elements on any depth of the tree.
On the other hand the
ViewEncapsulation.ShadowDom
changes the component's DOM structure by "hiding" DOM elements inside
ShadowRoot
elements. Such DOM manipulations do prevent some of the animations implementation to work properly since it relies on simple DOM structures and doesn't take
ShadowRoot
elements into account. Therefore it is advised to avoid applying animations to views incorporating components using the ShadowDom view encapsulation.
Animation sequence summary
link
Angular functions for animating multiple elements start with
query()
to find inner elements; for example, gathering all images within a
<div>
.
The remaining functions,
stagger()
,
group()
, and
sequence()
, apply cascades or let you control how multiple animation steps are applied.
More on Angular animations
link
You might also be interested in the following:
Introduction to Angular animations
Transition and triggers
Reusable animations
Route transition animations
Last reviewed on Mon Feb 28 2022
Stay Ahead in Today’s Competitive Market!
Unlock your company’s full potential with a Virtual Delivery Center (VDC). Gain specialized expertise, drive
seamless operations, and scale effortlessly for long-term success.
import{Component,Input}from'@angular/core';import{Hero}from'./hero';@Component({
selector:'app-hero-child',template:`
<h3>{{hero.name}} says:</h3>
<p>I, {{hero.name}}, am at your service, {{masterName}}.</p>
`})exportclassHeroChildComponent{@Input() hero!:Hero;@Input('master') masterName ='';}
The second
@Input
aliases the child component property name
masterName
as
'master'
.
The
HeroParentComponent
nests the child
HeroChildComponent
inside an
*ngFor
repeater, binding its
master
string property to the child's
master
alias, and each iteration's
hero
instance to the child's
hero
property.
import{Component,Input,OnChanges,SimpleChanges}from'@angular/core';@Component({
selector:'app-version-child',template:`
<h3>Version {{major}}.{{minor}}</h3>
<h4>Change log:</h4>
<ul>
<li *ngFor="let change of changeLog">{{change}}</li>
</ul>
`})exportclassVersionChildComponentimplementsOnChanges{@Input() major =0;@Input() minor =0;
changeLog:string[]=[];
ngOnChanges(changes:SimpleChanges){const log:string[]=[];for(const propName in changes){const changedProp = changes[propName];const to = JSON.stringify(changedProp.currentValue);if(changedProp.isFirstChange()){
log.push(`Initial value of ${propName} set to ${to}`);}else{constfrom= JSON.stringify(changedProp.previousValue);
log.push(`${propName} changed from ${from} to ${to}`);}}this.changeLog.push(log.join(', '));}}
The
VersionParentComponent
supplies the
minor
and
major
values and binds buttons to methods that change them.
import{Component}from'@angular/core';@Component({
selector:'app-version-parent',template:`
<h2>Source code version</h2>
<button type="button" (click)="newMinor()">New minor version</button>
<button type="button" (click)="newMajor()">New major version</button>
<app-version-child [major]="major" [minor]="minor"></app-version-child>
`})exportclassVersionParentComponent{
major =1;
minor =23;
newMinor(){this.minor++;}
newMajor(){this.major++;this.minor =0;}}
Here's the output of a button-pushing sequence:
Test it for Intercept input property changes with
ngOnChanges()
link
Test that
both
input properties are set initially and that button clicks trigger the expected
ngOnChanges
calls and values:
component-interaction/e2e/src/app.e2e-spec.ts
// ...// Test must all execute in this exact order
it('should set expected initial values',async()=>{const actual =await getActual();const initialLabel ='Version 1.23';const initialLog ='Initial value of major set to 1, Initial value of minor set to 23';
expect(actual.label).toBe(initialLabel);
expect(actual.count).toBe(1);
expect(await actual.logs.get(0).getText()).toBe(initialLog);});
it("should set expected values after clicking 'Minor' twice",async()=>{const repoTag = element(by.tagName('app-version-parent'));const newMinorButton = repoTag.all(by.tagName('button')).get(0);await newMinorButton.click();await newMinorButton.click();const actual =await getActual();const labelAfter2Minor ='Version 1.25';const logAfter2Minor ='minor changed from 24 to 25';
expect(actual.label).toBe(labelAfter2Minor);
expect(actual.count).toBe(3);
expect(await actual.logs.get(2).getText()).toBe(logAfter2Minor);});
it("should set expected values after clicking 'Major' once",async()=>{const repoTag = element(by.tagName('app-version-parent'));const newMajorButton = repoTag.all(by.tagName('button')).get(1);await newMajorButton.click();const actual =await getActual();const labelAfterMajor ='Version 2.0';const logAfterMajor ='major changed from 1 to 2, minor changed from 23 to 0';
expect(actual.label).toBe(labelAfterMajor);
expect(actual.count).toBe(2);
expect(await actual.logs.get(1).getText()).toBe(logAfterMajor);});asyncfunction getActual(){const versionTag = element(by.tagName('app-version-child'));const label =await versionTag.element(by.tagName('h3')).getText();const ul = versionTag.element((by.tagName('ul')));const logs = ul.all(by.tagName('li'));return{
label,
logs,
count:await logs.count(),};}// ...
Back to top
Parent listens for child event
link
The child component exposes an
EventEmitter
property with which it
emits
events when something happens.
The parent binds to that event property and reacts to those events.
The child's
EventEmitter
property is an
output property
, typically adorned with an @Output() decorator as seen in this
VoterComponent
:
Parent interacts with child using
local variable
link
A parent component cannot use data binding to read child properties or invoke child methods.
Do both by creating a template reference variable for the child element and then reference that variable
within the parent template
as seen in the following example.
The following is a child
CountdownTimerComponent
that repeatedly counts down to zero and launches a rocket.
The
start
and
stop
methods control the clock and a countdown status message displays in its own template.
import{Component}from'@angular/core';import{CountdownTimerComponent}from'./countdown-timer.component';@Component({
selector:'app-countdown-parent-lv',template:`
<h3>Countdown to Liftoff (via local variable)</h3>
<button type="button" (click)="timer.start()">Start</button>
<button type="button" (click)="timer.stop()">Stop</button>
<div class="seconds">{{timer.seconds}}</div>
<app-countdown-timer #timer></app-countdown-timer>
`,
styleUrls:['../assets/demo.css']})exportclassCountdownLocalVarParentComponent{}
The parent component cannot data bind to the child's
start
and
stop
methods nor to its
seconds
property.
Place a local variable,
#timer
, on the tag
<app-countdown-timer>
representing the child component.
That gives you a reference to the child component and the ability to access
any of its properties or methods
from within the parent template.
This example wires parent buttons to the child's
start
and
stop
and uses interpolation to display the child's
seconds
property.
Here, the parent and child are working together.
Test it for Parent interacts with child using
local variable
link
Test that the seconds displayed in the parent template match the seconds displayed in the child's status message.
Test also that clicking the
Stop
button pauses the countdown timer:
component-interaction/e2e/src/app.e2e-spec.ts
// ...// The tests trigger periodic asynchronous operations (via `setInterval()`), which will prevent// the app from stabilizing. See https://angular.io/api/core/ApplicationRef#is-stable-examples// for more details.// To allow the tests to complete, we will disable automatically waiting for the Angular app to// stabilize.
beforeEach(()=> browser.waitForAngularEnabled(false));
afterEach(()=> browser.waitForAngularEnabled(true));
it('timer and parent seconds should match',async()=>{const parent = element(by.tagName(parentTag));const startButton = parent.element(by.buttonText('Start'));const seconds = parent.element(by.className('seconds'));const timer = parent.element(by.tagName('app-countdown-timer'));await startButton.click();// Wait for `<app-countdown-timer>` to be populated with any text.await browser.wait(()=> timer.getText(),2000);
expect(await timer.getText()).toContain(await seconds.getText());});
it('should stop the countdown',async()=>{const parent = element(by.tagName(parentTag));const startButton = parent.element(by.buttonText('Start'));const stopButton = parent.element(by.buttonText('Stop'));const timer = parent.element(by.tagName('app-countdown-timer'));await startButton.click();
expect(await timer.getText()).not.toContain('Holding');await stopButton.click();
expect(await timer.getText()).toContain('Holding');});// ...
Back to top
Parent calls an
@ViewChild()
link
The
local variable
approach is straightforward.
But it is limited because the parent-child wiring must be done entirely within the parent template.
The parent component
itself
has no access to the child.
You can't use the
local variable
technique if the parent component's
class
relies on the child component's
class
.
The parent-child relationship of the components is not established within each component's respective
class
with the
local variable
technique.
Because the
class
instances are not connected to one another, the parent
class
cannot access the child
class
properties and methods.
When the parent component
class
requires that kind of access,
inject
the child component into the parent as a
ViewChild
.
The following example illustrates this technique with the same Countdown Timer example.
Neither its appearance nor its behavior changes.
The child CountdownTimerComponent is the same as well.
The switch from the
local variable
to the
ViewChild
technique is solely for the purpose of demonstration.
Here is the parent,
CountdownViewChildParentComponent
:
import{AfterViewInit,ViewChild}from'@angular/core';import{Component}from'@angular/core';import{CountdownTimerComponent}from'./countdown-timer.component';@Component({
selector:'app-countdown-parent-vc',template:`
<h3>Countdown to Liftoff (via ViewChild)</h3>
<button type="button" (click)="start()">Start</button>
<button type="button" (click)="stop()">Stop</button>
<div class="seconds">{{ seconds() }}</div>
<app-countdown-timer></app-countdown-timer>
`,
styleUrls:['../assets/demo.css']})exportclassCountdownViewChildParentComponentimplementsAfterViewInit{@ViewChild(CountdownTimerComponent)private timerComponent!:CountdownTimerComponent;
seconds(){return0;}
ngAfterViewInit(){// Redefine `seconds()` to get from the `CountdownTimerComponent.seconds` ...// but wait a tick first to avoid one-time devMode// unidirectional-data-flow-violation error
setTimeout(()=>this.seconds =()=>this.timerComponent.seconds,0);}
start(){this.timerComponent.start();}
stop(){this.timerComponent.stop();}}
It takes a bit more work to get the child view into the parent component
class
.
First, you have to import references to the
ViewChild
decorator and the
AfterViewInit
lifecycle hook.
Next, inject the child
CountdownTimerComponent
into the private
timerComponent
property using the
@ViewChild
property decoration.
The
#timer
local variable is gone from the component metadata.
Instead, bind the buttons to the parent component's own
start
and
stop
methods and present the ticking seconds in an interpolation around the parent component's
seconds
method.
These methods access the injected timer component directly.
The
ngAfterViewInit()
lifecycle hook is an important wrinkle.
The timer component isn't available until
after
Angular displays the parent view.
So it displays
0
seconds initially.
Then Angular calls the
ngAfterViewInit
lifecycle hook at which time it is
too late
to update the parent view's display of the countdown seconds.
Angular's unidirectional data flow rule prevents updating the parent view's in the same cycle.
The application must
wait one turn
before it can display the seconds.
Use
setTimeout()
to wait one tick and then revise the
seconds()
method so that it takes future values from the timer component.
Test it for Parent calls an
@ViewChild()
link
Use the same countdown timer tests as before.
Back to top
Parent and children communicate using a service
link
A parent component and its children share a service whose interface enables bidirectional communication
within the family
.
The scope of the service instance is the parent component and its children.
Components outside this component subtree have no access to the service or their communications.
This
MissionService
connects the
MissionControlComponent
to multiple
AstronautComponent
children.
The
MissionControlComponent
both provides the instance of the service that it shares with its children (through the
providers
metadata array) and injects that instance into itself through its constructor:
import{Component}from'@angular/core';import{MissionService}from'./mission.service';@Component({
selector:'app-mission-control',template:`
<h2>Mission Control</h2>
<button type="button" (click)="announce()">Announce mission</button>
<app-astronaut
*ngFor="let astronaut of astronauts"
[astronaut]="astronaut">
</app-astronaut>
<h3>History</h3>
<ul>
<li *ngFor="let event of history">{{event}}</li>
</ul>
`,
providers:[MissionService]})exportclassMissionControlComponent{
astronauts =['Lovell','Swigert','Haise'];
history:string[]=[];
missions =['Fly to the moon!','Fly to mars!','Fly to Vegas!'];
nextMission =0;constructor(private missionService:MissionService){
missionService.missionConfirmed$.subscribe(
astronaut =>{this.history.push(`${astronaut} confirmed the mission`);});}
announce(){const mission =this.missions[this.nextMission++];this.missionService.announceMission(mission);this.history.push(`Mission "${mission}" announced`);if(this.nextMission >=this.missions.length){this.nextMission =0;}}}
The
AstronautComponent
also injects the service in its constructor.
Each
AstronautComponent
is a child of the
MissionControlComponent
and therefore receives its parent's service instance:
Notice that this example captures the
subscription
and
unsubscribe()
when the
AstronautComponent
is destroyed.
This is a memory-leak guard step.
There is no actual risk in this application because the lifetime of a
AstronautComponent
is the same as the lifetime of the application itself.
That
would not
always be true in a more complex application.
You don't add this guard to the
MissionControlComponent
because, as the parent,
it controls the lifetime of the
MissionService
.
The
History
log demonstrates that messages travel in both directions between the parent
MissionControlComponent
and the
AstronautComponent
children, facilitated by the service:
Test it for Parent and children communicate using a service
link
Tests click buttons of both the parent
MissionControlComponent
and the
AstronautComponent
children and verify that the history meets expectations:
component-interaction/e2e/src/app.e2e-spec.ts
// ...
it('should announce a mission',async()=>{const missionControl = element(by.tagName('app-mission-control'));const announceButton = missionControl.all(by.tagName('button')).get(0);const history = missionControl.all(by.tagName('li'));await announceButton.click();
expect(await history.count()).toBe(1);
expect(await history.get(0).getText()).toMatch(/Mission.* announced/);});
it('should confirm the mission by Lovell',async()=>{await testConfirmMission(1,'Lovell');});
it('should confirm the mission by Haise',async()=>{await testConfirmMission(3,'Haise');});
it('should confirm the mission by Swigert',async()=>{await testConfirmMission(2,'Swigert');});asyncfunction testConfirmMission(buttonIndex: number, astronaut:string){const missionControl = element(by.tagName('app-mission-control'));const announceButton = missionControl.all(by.tagName('button')).get(0);const confirmButton = missionControl.all(by.tagName('button')).get(buttonIndex);const history = missionControl.all(by.tagName('li'));await announceButton.click();await confirmButton.click();
expect(await history.count()).toBe(2);
expect(await history.get(1).getText()).toBe(`${astronaut} confirmed the mission`);}// ...