{ "id": "guide/animations", "title": "Introduction to Angular animations", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Introduction to Angular animationslink

\n

Animation provides the illusion of motion: HTML elements change styling over time. Well-designed animations can make your application more fun and easier to use, but they aren't just cosmetic. Animations can improve your app and user experience in a number of ways:

\n\n

Typically, animations involve multiple style transformations over time. An HTML element can move, change color, grow or shrink, fade, or slide off the page. These changes can occur simultaneously or sequentially. You can control the timing of each transformation.

\n

Angular's animation system is built on CSS functionality, which means you can animate any property that the browser considers animatable. This includes positions, sizes, transforms, colors, borders, and more. The W3C maintains a list of animatable properties on its CSS Transitions page.

\n

About this guidelink

\n

This guide covers the basic Angular animation features to get you started on adding Angular animations to your project.

\n

The features described in this guide — and the more advanced features described in the related Angular animations guides — are demonstrated in an example app available as a .

\n

Prerequisiteslink

\n

The guide assumes that you're familiar with building basic Angular apps, as described in the following sections:

\n\n

Getting startedlink

\n

The main Angular modules for animations are @angular/animations and @angular/platform-browser. When you create a new project using the CLI, these dependencies are automatically added to your project.

\n

To get started with adding Angular animations to your project, import the animation-specific modules along with standard Angular functionality.

\n

Step 1: Enabling the animations modulelink

\n

Import BrowserAnimationsModule, which introduces the animation capabilities into your Angular root application module.

\n\nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\n\n@NgModule({\n imports: [\n BrowserModule,\n BrowserAnimationsModule\n ],\n declarations: [ ],\n bootstrap: [ ]\n})\nexport class AppModule { }\n\n\n\n
\n

Note: When you use the CLI to create your app, the root application module app.module.ts is placed in the src/app folder.

\n
\n

Step 2: Importing animation functions into component fileslink

\n

If you plan to use specific animation functions in component files, import those functions from @angular/animations.

\n\nimport { Component, HostBinding } from '@angular/core';\nimport {\n trigger,\n state,\n style,\n animate,\n transition,\n // ...\n} from '@angular/animations';\n\n\n\n
\n

Note: See a summary of available animation functions at the end of this guide.

\n
\n

Step 3: Adding the animation metadata propertylink

\n

In the component file, add a metadata property called animations: within the @Component() decorator. You put the trigger that defines an animation within the animations metadata property.

\n\n@Component({\n selector: 'app-root',\n templateUrl: 'app.component.html',\n styleUrls: ['app.component.css'],\n animations: [\n // animation triggers go here\n ]\n})\n\n\n

Animating a simple transitionlink

\n

Let's animate a simple transition that changes a single HTML element from one state to another. For example, you can specify that a button displays either Open or Closed based on the user's last action. When the button is in the open state, it's visible and yellow. When it's the closed state, it's transparent and green.

\n

In HTML, these attributes are set using ordinary CSS styles such as color and opacity. In Angular, use the style() function to specify a set of CSS styles for use with animations. You can collect a set of styles in an animation state, and give the state a name, such as open or closed.

\n
\n \"open\n
\n

Animation state and styleslink

\n

Use Angular's state() function to define different states to call at the end of each transition. This function takes two arguments: a unique name like open or closed and a style() function.

\n

Use the style() function to define a set of styles to associate with a given state name. Note that the style attributes must be in camelCase.

\n

Let's see how Angular's state() function works with the style⁣­(⁠) function to set CSS style attributes. In this code snippet, multiple style attributes are set at the same time for the state. In the open state, the button has a height of 200 pixels, an opacity of 1, and a background color of yellow.

\n\n// ...\nstate('open', style({\n height: '200px',\n opacity: 1,\n backgroundColor: 'yellow'\n})),\n\n\n

In the closed state, shown below, the button has a height of 100 pixels, an opacity of 0.5, and a background color of green.

\n\nstate('closed', style({\n height: '100px',\n opacity: 0.5,\n backgroundColor: 'green'\n})),\n\n\n

Transitions and timinglink

\n

In Angular, you can set multiple styles without any animation. However, without further refinement, the button instantly transforms with no fade, no shrinkage, or other visible indicator that a change is occurring.

\n

To make the change less abrupt, we need to define an animation transition to specify the changes that occur between one state and another over a period of time. The transition() function accepts two arguments: the first argument accepts an expression that defines the direction between two transition states, and the second argument accepts one or a series of animate() steps.

\n

Use the animate() function to define the length, delay, and easing of a transition, and to designate the style function for defining styles while transitions are taking place. You can also use the animate() function to define the keyframes() function for multi-step animations. These definitions are placed in the second argument of the animate() function.

\n

Animation metadata: duration, delay, and easinglink

\n

The animate() function (second argument of the transition function) accepts the timings and styles input parameters.

\n

The timings parameter takes a string defined in three parts.

\n
\n

animate ('duration delay easing')

\n
\n

The first part, duration, is required. The duration can be expressed in milliseconds as a simple number without quotes, or in seconds with quotes and a time specifier. For example, a duration of a tenth of a second can be expressed as follows:

\n\n

The second argument, delay, has the same syntax as duration. For example:

\n\n

The third argument, easing, controls how the animation accelerates and decelerates during its runtime. For example, ease-in causes the animation to begin slowly, and to pick up speed as it progresses.

\n\n
\n

Note: See the Material Design website's topic on Natural easing curves for general information on easing curves.

\n
\n

This example provides a state transition from open to closed with a one second transition between states.

\n\ntransition('open => closed', [\n animate('1s')\n]),\n\n\n

In the code snippet above, the => operator indicates unidirectional transitions, and <=> is bidirectional. Within the transition, animate() specifies how long the transition takes. In this case, the state change from open to closed takes one second, expressed here as 1s.

\n

This example adds a state transition from the closed state to the open state with a 0.5 second transition animation arc.

\n\ntransition('closed => open', [\n animate('0.5s')\n]),\n\n\n
\n

Note: Some additional notes on using styles within state and transition functions.

\n
\n\n\n

Triggering the animationlink

\n

An animation requires a trigger, so that it knows when to start. The trigger() function collects the states and transitions, and gives the animation a name, so that you can attach it to the triggering element in the HTML template.

\n

The trigger() function describes the property name to watch for changes. When a change occurs, the trigger initiates the actions included in its definition. These actions can be transitions or other functions, as we'll see later on.

\n

In this example, we'll name the trigger openClose, and attach it to the button element. The trigger describes the open and closed states, and the timings for the two transitions.

\n
\n \"triggering\n
\n
\n

Note: Within each trigger() function call, an element can only be in one state at any given time. However, it's possible for multiple triggers to be active at once.

\n
\n

Defining animations and attaching them to the HTML templatelink

\n

Animations are defined in the metadata of the component that controls the HTML element to be animated. Put the code that defines your animations under the animations: property within the @Component() decorator.

\n\n@Component({\n selector: 'app-open-close',\n animations: [\n trigger('openClose', [\n // ...\n state('open', style({\n height: '200px',\n opacity: 1,\n backgroundColor: 'yellow'\n })),\n state('closed', style({\n height: '100px',\n opacity: 0.5,\n backgroundColor: 'green'\n })),\n transition('open => closed', [\n animate('1s')\n ]),\n transition('closed => open', [\n animate('0.5s')\n ]),\n ]),\n ],\n templateUrl: 'open-close.component.html',\n styleUrls: ['open-close.component.css']\n})\nexport class OpenCloseComponent {\n isOpen = true;\n\n toggle() {\n this.isOpen = !this.isOpen;\n }\n\n}\n\n\n

When you've defined an animation trigger for a component, you can attach it to an element in that component's template by wrapping the trigger name in brackets and preceding it with an @ symbol. Then, you can bind the trigger to a template expression using standard Angular property binding syntax as shown below, where triggerName is the name of the trigger, and expression evaluates to a defined animation state.

\n\n<div [@triggerName]=\"expression\">...</div>;\n\n

The animation is executed or triggered when the expression value changes to a new state.

\n

The following code snippet binds the trigger to the value of the isOpen property.

\n\n<div [@openClose]=\"isOpen ? 'open' : 'closed'\" class=\"open-close-container\">\n <p>The box is now {{ isOpen ? 'Open' : 'Closed' }}!</p>\n</div>\n\n\n

In this example, when the isOpen expression evaluates to a defined state of open or closed, it notifies the trigger openClose of a state change. Then it's up to the openClose code to handle the state change and kick off a state change animation.

\n

For elements entering or leaving a page (inserted or removed from the DOM), you can make the animations conditional. For example, use *ngIf with the animation trigger in the HTML template.

\n
\n

Note: In the component file, set the trigger that defines the animations as the value of the animations: property in the @Component() decorator.

\n

In the HTML template file, use the trigger name to attach the defined animations to the HTML element to be animated.

\n
\n

Code reviewlink

\n

Here are the code files discussed in the transition example.

\n\n\n\n@Component({\n selector: 'app-open-close',\n animations: [\n trigger('openClose', [\n // ...\n state('open', style({\n height: '200px',\n opacity: 1,\n backgroundColor: 'yellow'\n })),\n state('closed', style({\n height: '100px',\n opacity: 0.5,\n backgroundColor: 'green'\n })),\n transition('open => closed', [\n animate('1s')\n ]),\n transition('closed => open', [\n animate('0.5s')\n ]),\n ]),\n ],\n templateUrl: 'open-close.component.html',\n styleUrls: ['open-close.component.css']\n})\nexport class OpenCloseComponent {\n isOpen = true;\n\n toggle() {\n this.isOpen = !this.isOpen;\n }\n\n}\n\n\n\n\n<div [@openClose]=\"isOpen ? 'open' : 'closed'\" class=\"open-close-container\">\n <p>The box is now {{ isOpen ? 'Open' : 'Closed' }}!</p>\n</div>\n\n\n\n\n:host {\n display: block;\n}\n\n.open-close-container {\n border: 1px solid #dddddd;\n margin-top: 1em;\n padding: 20px 20px 0px 20px;\n color: #000000;\n font-weight: bold;\n font-size: 20px;\n}\n\n\n\n\n\n

Summarylink

\n

You learned to add animation to a simple transition between two states, using style() and state() along with animate() for the timing.

\n

You can learn about more advanced features in Angular animations under the Animation section, beginning with advanced techniques in transition and triggers.

\n\n

Animations API summarylink

\n

The functional API provided by the @angular/animations module provides a domain-specific language (DSL) for creating and controlling animations in Angular applications. See the API reference for a complete listing and syntax details of the core functions and related data structures.

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nFunction name\n\nWhat it does\n
trigger()Kicks off the animation and serves as a container for all other animation function calls. HTML template binds to triggerName. Use the first argument to declare a unique trigger name. Uses array syntax.
style()Defines one or more CSS styles to use in animations. Controls the visual appearance of HTML elements during animations. Uses object syntax.
state()Creates a named set of CSS styles that should be applied on successful transition to a given state. The state can then be referenced by name within other animation functions.
animate()Specifies the timing information for a transition. Optional values for delay and easing. Can contain style() calls within.
transition()Defines the animation sequence between two named states. Uses array syntax.
keyframes()Allows a sequential change between styles within a specified time interval. Use within animate(). Can include multiple style() calls within each keyframe(). Uses array syntax.
group()Specifies a group of animation steps (inner animations) to be run in parallel. Animation continues only after all inner animation steps have completed. Used within sequence() or transition().
query()Use to find one or more inner HTML elements within the current element.
sequence()Specifies a list of animation steps that are run sequentially, one by one.
stagger()Staggers the starting time for animations for multiple elements.
animation()Produces a reusable animation that can be invoked from elsewhere. Used together with useAnimation().
useAnimation()Activates a reusable animation. Used with animation().
animateChild()Allows animations on child components to be run within the same timeframe as the parent.
\n

More on Angular animationslink

\n

You may also be interested in the following:

\n\n
\n

Check out this presentation, shown at the AngularConnect conference in November 2017, and the accompanying source code.

\n
\n\n \n
\n\n\n" }