Target Children Elements
Learn how to use the animateChild function of Angular animations to execute a child or multiple children's animations from its parent.
We'll cover the following
Problem
You might be wondering why we’d need to trigger a child’s animation through its parent if we can execute the child’s animation directly.
One of the common use cases of this functionality is when we have an *ngIf
directive attached to the parent, and each of the children has its animation triggers attached to it with their enter and leave animations. This isn’t a problem when the parent enters the DOM. All the children’s animations will be executed normally as they are added to the DOM. However, the :leave
animation of the child elements doesn’t work the same way. Because the *ngIf
is on the parent, once that value becomes false
, the children will immediately be removed from the DOM along with the parent without executing the children’s animation and waiting for it to complete.
Solution
Angular animations’ animateChild
function allows animations on child components to be run within the same timeframe as the parent. To address the exit animation problem above, the animateChild
function forces the parent to wait for the child elements’ animation to complete before removing them from the DOM.
How it works
By definition, the animateChild
function executes a queried inner animation element within an animation sequence.
The animateChild
function accepts one parameter— option
—and returns an AnimationAnimateChildMetadata
. The AnimationAnimateChildMetadata
is an object that encapsulates the child animation data that can be passed into the query
function. The code snippet below shows the expected parameter type (line 2) and return type (line 3) of the animateChild
function.
Get hands-on with 1400+ tech skills courses.