How To Implement Animation Effects In Angular 10

In this article, we will discuss  how to use the Animation functionalities in Angular 10 applications. Angular provides the functionality to create animation and activate those on the basis of different types of factors. We can implement animation on any HTML element and also activate those animations on the basis of different events. In this article, we are going to discuss the various animation samples and the different implementations in Angular. Animations in Angular Framework are mainly implemented inside the components using a set of functions (trigger, state, animate, transition, style) with the help of @angular/animations package. Animation styles are mainly used to defined CSS based rules, but they are also defined in TypeScript using the JSON object structure instead of using CSS files. With the help of Angular Animations, we can implement the physical appearance change of any element in an application with the help of different properties in a given time. Animation includes life to HTML elements and represents it as more interactive.
 

Overview in Angular Animation

 
Angular Animation (@angular/animations) is one of the most powerful modules in Angular Framework. Angular animations always provide a domain-specific language for defining and designing the web animation sequences for any HTML elements with multiple transformations over time and it can occur sequentially or in parallel. Angular animation always uses the native web animation APIs. The Angular animations are mainly based on the CSS based web transition functionality which means that any HTML objects which be styled or transformed through CSS, that can be also animation the same using the Angular Animations. In this way, it will provide must more control to the developer in designing the animation effects.
 
In Angular Framework, Angular animation mainly used BrowserAnimationModule for animation reasons. So, Angular animation implementations can be divided into 4 steps as
below, 
  1. Need to evaluate data binding expression which tells Angular about which animation state the main host element is assigned to.
  2. Data binding targets intimate Angular which animation target defines CSS styles for the element state.
  3. Now state intimate Angular which CSS styles should be applied to the element
  4. Finally, Transition instructs Angular how it should apply the specified CSS styles when there is a state change in the application.
Angular animation provides a set of properties through which HTML elements get into motion. It is a very fancy way to display HTML elements on a website or any application. With the help of the Angular framework, we can create animation just similar to CSS animation. Angular animation is built on top of the standard Web Animation API (WAAPI) and can run natively on any browsers which support it.
 
So, in the Angular animations, the style function is one of the most important parts of the animation process. Through this function, we can specify which type of styles need to apply to the target element at a certain state. This function can accept both types of conventions related to defining the style property for an HTML element. It supports the Javascript naming convention for CSS which needs to use camelCase keys.
  1. style({  
  2.           backgroundColor: "green",  
  3.       })  
Also, it supports the CSS property naming convention (dashed case).
  1. style({  
  2.           "background-color""green",  
  3.         })  

Why need to use Angular Animation?

 
Now, it is a very common question that Why we need to use Angular Animation in place CSS-based animation? Now, there are many different opinions against this question. In some scenario, CSS based animation is much better compared to the Angular Animation and vice – versa. Angular always provides simplicity in comparison with CSS while performing complex type animations on a single HTML element at various states or events. The browser normally uses the GPU layers to process the animations so that the CPU can work on the main task. The Browser takes advantage of GPU speed boost by creating a GPU layer for that element when a change in a 3D characteristic like translate3d() or matrix3d() triggers the Browser.
 

How to use Angular Animation?

 
Now, in this section, we will discuss how to use Angular Animation in any application. So, to use the @angular/animations in our application, we need to follow the below steps,
  1. First, we need to verify that the @angular/animations package is installed and listed as a dependency in our package.json file. Normally, it is added by default when we create any new project using Angular CLI.
  2. If it is not added in the package.json file, then need to install by running the command npm install @angular/animations.
  3. Now open the angular module file and import the BrowserAnimationModule within the defined angular module.
    1. import { BrowserModule } from '@angular/platform-browser';    
    2. import { NgModule } from '@angular/core';    
    3. import { FormsModule } from '@angular/forms';    
    4. import { HttpClientModule } from '@angular/common/http';    
    5. import { BrowserAnimationsModule } from '@angular/platform-browser/animations'    
    6.     
    7. import { AppRoutingModule} from './app-routing.module';    
    8. import { AppComponent } from './app.component';    
    9.     
    10. import { HomeComponent } from './home/home.component';    
    11.     
    12. @NgModule({    
    13.   declarations: [    
    14.     AppComponent, HomeComponent,    
    15.         
    16.   ],    
    17.   imports: [    
    18.     BrowserModule,    
    19.     AppRoutingModule,    
    20.     BrowserAnimationsModule,    
    21.     FormsModule,    
    22.     HttpClientModule    
    23.   ],    
    24.   providers: [],    
    25.   bootstrap: [AppComponent]    
    26. })    
    27. export class AppModule { }    

Concept of Animation States & Transition between State Change

 
Now, in this section, we will discuss some basic sample use cases related to the Angular Animation module. So, before start demonstrating those examples, first we need to understand the basic working mechanism of Angular animation and its related states.
 
Animation States
 
Angular provides us the facility to define a style and transition which need to be applied when an elements state changes. Angular always provides 3 different states which we can implement in our animation code –
  • Wildcard (*)
    This is the default state of the element. It indicates all states of the element. Say for example, * => active means that a state can be changed to an active state from any state or vice-versa.

  • Void (void)
    This state is used when we create the element but that particular element is not a part of the DOM or the element is already removed from the DOM part.

  • Custom
    It can be any custom name to indicate a certain state of the element like ‘active’, ‘inactive’, ‘basic’, etc.
Transitions Between State Change
 
So, before we start the angular animation, we always need to define the different states for the HTML element to perform state change between different transitions. It is the first parameter that needs to be passed into the state function. We also need to define the style within this parameter so that it can be applied to the HTML element for that mentioned state. Now, for animating the transition between different state, we need to pass the transition function by mentioning the two states (i.e. from state and target state) in which transition need to be applied.
  1. import { trigger, state, style, animate, transition } from '@angular/animations';  
  2.   
  3. @Component({  
  4.     selector: 'animation-demo',  
  5.     template: `  
  6.           <div class="mybox mx-auto" [@enabledStateChange]="enabledStateChange"></div>    
  7.           <div class="msgbox mx-auto">{{msg}}</div>  
  8.       `,  
  9.   animations: [  
  10.     trigger('enabledStateChange', [  
  11.       state( 'default', style({  
  12.             opacity: 1,  
  13.         })  
  14.     ),  
  15.     state( 'disabled', style({  
  16.             opacity: 0.5,  
  17.         })  
  18.       ),  
  19.       transition('* => *', animate('300ms ease-out')),  
  20.     ])  
  21.   ]  
  22. })  
Now, in the below section, we briefly discuss the different parameters of the animation method,
  • trigger – This parameter accepts a name for the animation trigger and also an array of state and transition methods to implement the configuration for the animation.
  • state – This parameter always accepts the name related to the state and the styles which should be applied when the HTML element is in a specified state.
  • style – This parameter is used to define the CSS styles which need to be applied to the HTML element.
  • transition – This parameter mentioned the configuration for the transitioning between the different states and their direction.
  • animate – This parameter specifies the duration of the animation and any additional CSS animation properties such as easing.

Demo 1 - Basic Animation Sample

 
Now, in this demo, we will demonstrate the basic animation sample against the event. In this sample, we create a basic rectangle shape objects using the CSS property. Now when clicked the Animation button, it will perform some basic animation with the help of background color & also scaling the objects in the certain mention ration. Also, we will use the delay property of the CSS to show the animation properly.
 
For this purpose, we need to create the below-mentioned component in our project,
 
basic.animation.component.html
  1. <h1>Animation Basics</h1>  
  2.   
  3. <div class="container-fluid">  
  4.     <div class="row">  
  5.         <div class="col-2">  
  6.             <div class="btn-group-vertical btn-block" style="margin-top:1rem;">  
  7.                 <a (click)="changeState('original')" class="btn btn-primary active">Return to Original</a>              
  8.                 <a (click)="changeState('basic')" class="btn btn-primary">Animation</a>              
  9.                 <a (click)="changeState('delaying')" class="btn btn-primary">Animation with Delay</a>  
  10.             </div>  
  11.         </div>  
  12.         <div class="col-5">  
  13.             <demo-animation [currentState]="switchState"></demo-animation>  
  14.         </div>  
  15.         <div class="col-5"></div>  
  16.     </div>  
  17. </div>  
basic.animation.component.ts
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'basic-animation',  
  5.   templateUrl: './basic.animation.component.html'  
  6. })  
  7.   
  8. export class BasicAnimationComponent {  
  9.     
  10.   public switchState:string='original';  
  11.   
  12.   public changeState(state:string):void{  
  13.     this.switchState = state;  
  14.     console.log(this.switchState);  
  15.   }  
  16. }  
demo.animation.component.ts
  1. import { Component, Input } from '@angular/core';  
  2. import { trigger, state, style, animate, transition, keyframes, group } from '@angular/animations';  
  3.   
  4. @Component({  
  5.   selector: 'demo-animation',  
  6.   template: `  
  7.         <div class="mybox mx-auto" [@changeState]="currentState" ></div>  
  8.     `,  
  9.   styles :[`  
  10.     .mybox {  
  11.         background-color : #47748f;  
  12.         width : 200px;  
  13.         height : 200px;  
  14.         border-radius : 6px;  
  15.         margin : 6rem  
  16.     }  
  17.     .msgbox {  
  18.         margin: 2rem;  
  19.         padding-top:2rem;  
  20.         font-size: 1.8rem;  
  21.         text-align: center;  
  22.     }  
  23.   `],  
  24.   animations: [  
  25.     trigger('changeState', [  
  26.         state('original', style({  
  27.             backgroundColor: '#47748f',  
  28.             transform: 'scale(1)'  
  29.         })),  
  30.         state('basic', style({  
  31.             backgroundColor: '#440000',  
  32.             transform: 'scale(1.4)'  
  33.         })),  
  34.         state('delaying', style({  
  35.             backgroundColor: '#812170',  
  36.             transform: 'scale(1.6)'  
  37.         })),  
  38.         transition('* => basic', animate('800ms')),  
  39.         transition('* => original', animate('200ms')),  
  40.         transition('* => delaying', animate('800ms 2000ms ease-out'))  
  41.     ])]  
  42. })  
  43.   
  44. export class DemoAnimationComponent {  
  45.     @Input() currentState : string;     
  46. }  
Now, include these components in the app.module.ts file and then execute in the application.
 
How To Implement Animation Effects In Angular 10
 

Demo 2 - Animation Against Mouse Events

 
Now in this demo, we will demonstrate animation against the mouse event like mouse-down or mouse-leave events. For this purpose, we need to create the below components,
 
container.animation.component.html
  1. <h1>Self-Contained Animation</h1>  
  2.   
  3. <div class="container-fluid">  
  4.     <div class="row">  
  5.         <div class="col-4">  
  6.             <mouse-animation></mouse-animation>  
  7.         </div>  
  8.     </div>  
  9. </div>  
container.animation.component.ts
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'container-animation',  
  5.   templateUrl: './container.animation.component.html'  
  6. })  
  7.   
  8. export class ContainerAnimationComponent {  
  9.   
  10.  
mouse.animation.component.ts
  1. import { Component } from '@angular/core';  
  2. import { trigger, state, style, animate, transition } from '@angular/animations';  
  3.   
  4. @Component({  
  5.   selector: 'mouse-animation',  
  6.   template: `  
  7.         <div class="mymouse mx-auto" (mouseenter)="changeMouseState('hover')" (mousedown)="changeMouseState('press')"   
  8.             (mouseleave)="changeMouseState('rest')" [@changeState]="currentState"></div>  
  9.     `,  
  10.   styles: [`  
  11.     .mymouse {  
  12.         background-color: #5c8f52;  
  13.         width: 100px;  
  14.         height: 100px;  
  15.         border-radius: 200px;  
  16.         margin: 6rem;  
  17.     }  
  18.   `],  
  19.   animations: [  
  20.     trigger('changeState', [  
  21.         state('rest', style({  
  22.             transform: 'scale(1)'  
  23.         })),  
  24.         state('hover',   style({  
  25.             transform: 'scale(1.8)'  
  26.         })),  
  27.         state('press',   style({  
  28.             transform: 'scale(3.0)',  
  29.             backgroundColor: '#8f5a7a'  
  30.         })),  
  31.         transition('rest => hover', animate('400ms ease-in')),  
  32.         transition('hover => rest', animate('200ms ease-out')),  
  33.         transition('hover => press', animate('400ms ease-in')),  
  34.         transition('press => rest', animate('200ms ease-out'))  
  35.     ])  
  36.   
  37. ]  
  38. })  
  39.   
  40. export class MouseAnimationComponent {  
  41.     currentState:string = "rest";  
  42.   
  43.     changeMouseState(state:string) :void {  
  44.         this.currentState = state;  
  45.     }  
  46.   
  47. }  
Now, include the above-mentioned component in the app.module.ts file and then execute the program in the browse,
 
How To Implement Animation Effects In Angular 10
 

Concept of Router Animation

 
Animations in Route transition is one of the coolest ways to add some life to the web application. Route Animation always indicates to the animations which are applied to view transitions during a route change. As per the Angular guideline, this needs to be done by defining a nested animation sequence in the top-level component that hosts the view and also the component which hosts the embedded views. In this way, we can apply nested router-outlets in our application. For the animation trigger, we just need to apply that against the div which contains the router-outlet.
 
To demonstrate this, we need to first wrap the router-outlet within a div element which will contain the trigger for the animation. After this, we need to assign an attribute directive in the router-outlet which contains the data about the active routes and needs to define their states which are then used to implement an animation state value to the animation trigger based on the configuration.
  1. <div class="page" [@routerAnimations]="prepareRouteTransition(outlet)">  
  2.       <router-outlet #outlet="outlet"></router-outlet>  
  3. </div>  
Now, we need to pass the outlet’s current state to our routeAnimations with the help of the router-outlet’s activedRoute property. This property will always be updated whenever any route navigation occurred and at the same time, it will trigger the animation.
  1. public prepareRouteTransition(outlet) : any {  
  2.     const animation = outlet.activatedRouteData['animation'] || {};  
  3.     return animation['value'] || null;  
  4.   }  
We can also pass the additional parameters through the router's data property if we need to implement variable animations.
 

Demo 3 - Router Animation

 
Now, in this demo, we will demonstrate the route animation. For that purpose, we need to add the routing module to our module. We will use the route navigation key against the Demo1 and Demo2 examples. For that purpose, we need to add the below component code –
 
app-routing.module.ts
  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3.   
  4. import { HomeComponent } from './home/home.component';  
  5. import { BasicAnimationComponent } from './01-basic-animations/basic.animation.component';  
  6. import { ContainerAnimationComponent } from './02-container-animations/container.animation.component';  
  7.   
  8. const routeData: Routes = [  
  9.     { path: '', redirectTo:'/home', pathMatch: 'full', data: {animation: { value: 'home',}} },  
  10.     { path: 'home', component: HomeComponent, data: {animation: { value: 'home',}} },    
  11.     { path: 'basic-animation', component: BasicAnimationComponent, data: {animation: { value: 'basic',}}  },   
  12.     { path: 'container-animation', component: ContainerAnimationComponent, data: {animation: { value: 'container',}}  }  
  13. ];  
  14.   
  15. @NgModule({  
  16.   imports: [RouterModule.forRoot(routeData)],  
  17.   exports: [RouterModule]  
  18. })  
  19. export class AppRoutingModule { }  
app.component.ts
  1. import { Component, ViewEncapsulation } from '@angular/core';  
  2. import { trigger, transition } from '@angular/animations';  
  3. import { slideAnimation } from './shared/animation';  
  4.   
  5. @Component({  
  6.   selector: 'app-root',  
  7.   templateUrl: './app.component.html',  
  8.   styleUrls: ['./app.component.css'],  
  9.   encapsulation: ViewEncapsulation.None,  
  10.     animations: [  
  11.         trigger('routerAnimations', [  
  12.             transition('* => *', slideAnimation)  
  13.         ])  
  14.     ]  
  15. })  
  16.   
  17. export class AppComponent {  
  18.   title = 'angular-animation-demo';  
  19.   
  20.   public prepareRouteTransition(outlet) : any {  
  21.     const animation = outlet.activatedRouteData['animation'] || {};  
  22.     return animation['value'] || null;  
  23.   }  
  24.   
  25. }  
app.component.html
  1. <nav class="navbar navbar-expand-lg fixed-top navbar-inverse mb-4" style="background-color:#920787;">  
  2.     <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"   
  3.             aria-expanded="false" aria-label="Toggle navigation">  
  4.       <span class="navbar-toggler-icon"></span>  
  5.     </button>    
  6.     <a class="navbar-brand" href="#" style="color: rgb(169, 235, 16);font-weight: 300;">Animation Demo</a>  
  7.   
  8.     <div class="collapse navbar-collapse" id="navbarSupportedContent">  
  9.       <ul class="navbar-nav mr-auto">  
  10.         <li class="nav-item">   
  11.             <a class="nav-link" routerLink="/home" routerLinkActive="active" style="color: white;">Home</a>  
  12.         </li>   
  13.         <li  class="nav-item"><a class="nav-link" routerLink="/basic-animation" routerLinkActive="active" style="color: white;">Demo 1</a></li>  
  14.         <li  class="nav-item"><a class="nav-link" routerLink="/container-animation" routerLinkActive="active" style="color: white;">Demo 2</a></li>  
  15.           
  16.       </ul>  
  17.     </div>  
  18. </nav>  
  19. <div class="page" style="padding-top: 30px;">  
  20.     <div class="page" [@routerAnimations]="prepareRouteTransition(outlet)">  
  21.       <router-outlet #outlet="outlet"></router-outlet>  
  22.   </div>  
  23. </div>  
animation.ts (for mentioned the common route style related effects)
  1. import { animate, animation, style } from '@angular/animations';  
  2.   
  3. export var slideAnimation = animation([  
  4.     style({ opacity: 0, position: 'absolute', left: 0, right: 0, transform: 'translate3d(-100%,0,0)' }),  
  5.     animate('400ms ease-in-out', style({ opacity: 1, transform: 'translate3d(0%,0,0)' })),  
  6. ])  
Now, execute the program and check the output in browse,
 
How To Implement Animation Effects In Angular 10
 

Conclusion

 
In this article, we discussed how to implement the animations using the Angular Framework in any web application. Also, we discussed the basic concept of animation along with transition states, route animation, etc. I hope, this article will help you. Any feedback or query related to this article is most welcome.


Similar Articles