Animation Using Angular 6

Angular allows us to create animations which provides us similar native performance as CSS animations. In this article, we will learn how we can create animation using Angular 6.

Introduction 

Animation is defined as the transition from an initial state to a final state. It is an integral part of any modern web application. Animation not only help us to create a great UI but it also makes the application interesting and fun to use. A well-structured animation keeps the user glued to the application and enhances the user experience.

Angular allows us to create animations which provide us the similar native performance as CSS animations. In this article, we will learn how we can create animation using Angular 6.

We will use Visual Studio Code for our demo.

Prerequisites

Install VS Code and Angular CLI.

If you are new to Angular, then refer to my previous article Getting Started With Angular 6.0 to set Angular 6 development environment your machine.

Source Code

Download the source code from GitHub.

Understanding Angular Animation States

Animation is a transition from one state of the element to another state. Angular defined three different states for an element.

  1. Void state
    Void state represents the state of an element which is not part of the DOM. This state occurs when an element is created but not yet placed in the DOM or the element is removed from the DOM. This state is useful when we want to create animation while adding or removing an element from our DOM. To define this state in our code we use the keyword void.

  2. The wildcard state
    This is also known as the default state of the element. The styles defined for this state is applicable to the element regardless of its current animation state. To define this state in our code we use the * symbol.

  3. Custom state
    This is the custom state of the element and it needs to be defined explicitly in the code. To define this state in our code we can use any custom name of our choice.
Animation Transition Timing

To show the animation transition from one state to another we define animation transition timing in our application.

Angular provides us the following three timing properties:

Duration

This property represents the time our animation takes to complete from start (initial state) to finish (final state). We can define the duration of the animation in the following three ways: 
  • Using an integer value, which represents the time in milliseconds. E.g.- 500
  • Using a string value to represent the time in milliseconds. E.g. - '500ms'
  • Using a string value to represent the time in seconds. E.g. - '0.5s'
Delay

This property represents the time duration between the animation trigger and the beginning of the actual transition. This property also follows the same syntax as duration. To define the delay, we need to add the delay value after the duration value in a string format – '
Duration Delay'. Delay is an optional property.

e.g.
'0.3s 500ms'. This means the transition will wait for 500ms and then run for 0.3s

Easing

This property represents how the animation accelerates or decelerates during its execution. We can define the easing by adding it as the third variable in the string after duration and delay. If the delay value is not present, then easing will be the second value. This is also an optional property.

E.g.
  • '0.3s 500ms ease-in' – This means the transition will wait for 500ms and then run for 0.3s (300ms) with ease-in effect.
  • '300ms ease-out'. - This means the transition will run for 300ms (0.3s) with ease-out effect.
Creating the Angular 6 application
 
Open the command prompt in your machine and execute the following set of commands,
  • mkdir ngAnimationDemo
  • cd ngAnimationDemo
  • ng new ngAnimation
These commands will create a directory with name “ngAnimationDemo” and then create an Angular application with the name “ngAnimation” inside that directory.
 
Open the ngAnimation app using VS code. Now we will create our component.
 
Navigate to View >> Integrated Terminal. This will open a terminal window in VS Code.
 
Execute the following command to create the component.
  1. ng g c animationdemo  
This will create our component “animationdemo” inside /src/app folder.
 
To use Angular animation we need to import “BrowserAnimationsModule” which is an animation-specific module in our application. Open app.module.ts file and include the import definition as shown below:
  1. import { BrowserAnimationsModule } from '@angular/platform-browser/animations';  
  2. // other import definitions  
  3.   
  4. @NgModule({ imports: [BrowserAnimationsModule // other imports]})  
Understanding the Angular Animation Syntax
 
We will write our animation code inside the component’s metadata. The syntax for animation is as shown below,
  1. @Component({  
  2. // other component properties.  
  3.   animations: [  
  4.     trigger('triggerName'), [  
  5.       state('stateName', style())  
  6.       transition('stateChangeExpression', [Animation Steps])  
  7.     ]  
  8.   ]  
  9. })  

Here we will use a property called “animations”. This property will take an array as input. The array contains of one or more “trigger”. Each trigger has a unique name and an implementation. The state and transitions for our animation needs to be defined in the trigger implementation.

Each state function has a “stateName” defined to uniquely identify the state and a style function to show the style of an element in that state.

Each transition function has a “stateChangeExpression” defined to show the change of state of an element and the corresponding array of animation steps to show how the transition will take place. We can also include multiple trigger functions inside the animation property as comma separated values.

These functions trigger, state, and transition are defined in the "@angular/animations" module. Hence, we need to import this module in our component.
 
To apply animation on an element we need to include the trigger name in the element definition. Include the trigger name followed by @ symbol in the element tag. Refer to the sample code below,
  1. <div @changeSize></div>  

This will apply the trigger “changeSize” to the <div> element.

Let us create few animations to get a better understanding of the Angular animation concepts.

Change Size Animation

We will create an animation to change the size of a <div> element on a button click.

Open animationdemo.component.ts file and add the following import definition.
  1. import { trigger, state, style, animate, transition } from '@angular/animations';  
Add the following animation property definition in the component metadata.
  1. animations: [  
  2.   trigger('changeDivSize', [  
  3.     state('initial', style({  
  4.       backgroundColor: 'green',  
  5.       width: '100px',  
  6.       height: '100px'  
  7.     })),  
  8.     state('final', style({  
  9.       backgroundColor: 'red',  
  10.       width: '200px',  
  11.       height: '200px'  
  12.     })),  
  13.     transition('initial=>final', animate('1500ms')),  
  14.     transition('final=>initial', animate('1000ms'))  
  15.   ]),  
  16. ]  

Here we have defined a trigger “changeDivSize” and two state functions inside the trigger. The element will be of green color in the “initial” state and will be of red color with an increased width and height in the “final” state.

We have defined transitions for the state change. The transition from “initial” state to “final” will take 1500ms and from “final” state to “initial” will take 1000ms.

To change the state of our element we will define a function in the class definition of our component. Include the following code in the AnimationdemoComponent class.

  1. currentState = 'initial';  
  2.   
  3. changeState() {  
  4.   this.currentState = this.currentState === 'initial' ? 'final' : 'initial';  
  5. }  

Here we have defined a changeState method which will switch the state of the element.

Open animationdemo.component.html file and add the following code,

  1. <h3>Change the div size</h3>  
  2. <button (click)="changeState()">Change Size</button>  
  3. <br />  
  4. <div [@changeDivSize]=currentState></div>  
  5. <br />  

We have defined a button which will invoke the changeState function when clicked. We have defined a <div> element and applied the animation trigger “changeDivSize” to it. When we click on the button it will flip the state of the <div> element and the size of <div> will change with a transition effect.

Before executing the application, we need to include the reference to our Animationdemo component inside the app.component.html file.

Open app.component.html file. You can see we some default HTML code in this file. Delete all the code and put the selector of our component as shown below,

  1. <app-animationdemo></app-animationdemo>  

To execute the code run “ng serve” command in the VS code terminal window. After running this command, it will ask to open http://localhost:4200 in the browser. So, open any browser on your machine and navigate to this URL. You can see a webpage as shown below. Click on the button to see the animation.

Change Size Animation

Balloon effect animation

In the previous animation, the transition happened in two directions. In this section, we will learn how to change the size from all direction. It will be similar to inflating and deflating a balloon hence the name balloon effect animation.

Add the following trigger definition in the animation property.
  1. trigger('balloonEffect', [  
  2.    state('initial', style({  
  3.      backgroundColor: 'green',  
  4.      transform: 'scale(1)'  
  5.    })),  
  6.    state('final', style({  
  7.      backgroundColor: 'red',  
  8.      transform: 'scale(1.5)'  
  9.    })),  
  10.    transition('final=>initial', animate('1000ms')),  
  11.    transition('initial=>final', animate('1500ms'))  
  12.  ]),  

Here instead to defining the width and height property we are using the transform property to change the size from all directions. The transition will occur when the state of the element is changed. 

Add the following HTML code in app.component.html file.
  1. <h3>Balloon Effect</h3>  
  2. <div (click)="changeState()"   
  3.   style="width:100px;height:100px; border-radius: 100%; margin: 3rem; background-color: green"  
  4.   [@balloonEffect]=currentState>  
  5. </div>  

Here we have defined a div and applied the CSS style to make it a circle. Clicking on div will invoke the changeState method to switch the element’s state.

Open the browser to see the animation in action as shown below,

Balloon effect animation 

Fade In and Fade Out animation

Sometimes we want to show an animation while adding or removing an element on the DOM. We will see how to animate the adding and removing of an item to a list with fade-in and fade-out effect.

Add the following code inside the AnimationdemoComponent class definition for adding and removing the element in a list.
  1. listItem = [];  
  2. list_order: number = 1;  
  3.   
  4. addItem() {  
  5.   var listitem = "ListItem " + this.list_order;  
  6.   this.list_order++;  
  7.   this.listItem.push(listitem);  
  8. }  
  9. removeItem() {  
  10.   this.listItem.length -= 1;  
  11. }  

Add the following trigger definition in the animation property.

  1. trigger('fadeInOut', [  
  2.   state('void', style({  
  3.     opacity: 0  
  4.   })),  
  5.   transition('void <=> *', animate(1000)),  
  6. ]),  

Here we have defined the trigger “fadeInOut”.When the element is added to the DOM it is a transition from void to wildcard (*) state. This is denoted using void => *. When the element is removed from DOM it is a transition from wildcard (*) to void state. This is denoted using * => void.

When we use the same animation timing for both directions of the animation we use a shorthand syntax as <=>. As defined in this trigger, the animation from void => * and * => void will take 1000ms to complete.

Add the following HTML code in app.component.html file.
  1. <h3>Fade-In and Fade-Out animation</h3>  
  2.   
  3. <button (click)="addItem()">Add List</button>  
  4. <button (click)="removeItem()">Remove List</button>  
  5.   
  6. <div style="width:200px; margin-left: 20px">  
  7.   <ul>  
  8.     <li *ngFor="let list of listItem" [@fadeInOut]>  
  9.       {{list}}  
  10.     </li>  
  11.   </ul>  
  12. </div>  

Here we are defining two buttons to add and remove item to the list. We are binding the fadeInOut trigger to the <li> element, which will show a fade-in, and fade-out effect while being added and removed from the DOM.

Open the browser to see the animation in action as shown below,

Fade In and Fade Out animation 

Enter and Leave animation

While adding to the DOM, the element will enter the screen from left and while deleting, the element will leave the screen from the right.

The transition from void => * and * => void is very common. Therefore, Angular provides aliases for these animations,
  • for void => * we can use ':enter'
  • for * => void we can use ':leave'
The aliases make these transitions more readable and easier to understand.

Add the following trigger definition in the animation property,
  1. trigger('EnterLeave', [  
  2.   state('flyIn', style({ transform: 'translateX(0)' })),  
  3.   transition(':enter', [  
  4.     style({ transform: 'translateX(-100%)' }),  
  5.     animate('0.5s 300ms ease-in')  
  6.   ]),  
  7.   transition(':leave', [  
  8.     animate('0.3s ease-out', style({ transform: 'translateX(100%)' }))  
  9.   ])  
  10. ])  

Here we have defined the trigger “EnterLeave”. The ':enter' transition will wait for 300ms and then run for 0.5s with an ease-in effect. Whereas the ':leave transition will run for 0.3s with an ease-out effect.

Add the following HTML code in app.component.html file.
  1. <h3>Enter and Leave animation</h3>  
  2.   
  3. <button (click)="addItem()">Add List</button>  
  4. <button (click)="removeItem()">Remove List</button>  
  5.   
  6. <div style="width:200px; margin-left: 20px">  
  7.   <ul>  
  8.     <li *ngFor="let list of listItem" [@EnterLeave]="'flyIn'">  
  9.       {{list}}  
  10.     </li>  
  11.   </ul>  
  12. </div>  

Here we are defining two buttons to add and remove item to the list. We are binding the EnterLeave trigger to the <li> element that will show enter and leave effect while being added and removed from the DOM.

Open the browser to see the animation in action as shown below,

Enter and Leave animation 

Conclusion

In this article, we learned about the Angular 6 animations. We explored the concept of animation states and transitions. We also saw a few animations in action with the help of a sample application.

Please get the source code from GitHub and play around to get a better understanding.

You can also read other articles on my personal blog here.

See Also