Thursday, September 14, 2017

Animation in Angular 2

Angular 2 provides a group of great modules to show animations on your page. In this demo we'll show you a simple animation of moving a box div while changing its height and width in between.
Steps : 1
Import following modules in you component
1
import { Component, OnInit, trigger, state, style, transition, animate, group } from '@angular/core';
Step : 2
Add following code into @component decorative. Now in this divState will be actually div that will change when one state changes to another, we can also use void and wild card operators. '<=>' this symbol means that animation would trigger when either when normal state changes to highlight or highlight to normal. As shown below we can have animation inside animation as well.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
animations : [
      trigger('divState', [
      state('normal', style({
          'background-color''red',
          'transform''translateX(0px)'
      })),
      state('highlight', style({ // If "highlight" name is not given the style will be applied to void state
      'background-color''blue',
      'transform''translateX(100px)'
      })),
      transition('normal <=> highlight', [
          group([ // Syncronus animation
          animate(500, style({ 'width'"500px" })), // Animations in between transation and will revert back
          animate(500, style({ 'height'"500px" })),
          animate(1000, style({
          'border-radius''50px'
          }))
          ]),
          animate(500) // actual transition animation
      ])
      ])
  ]
Step 3 :
Now add the following in your HTML. Its just a simple box shape div, which animate on click of animate button. Notice, we also defined divState which was shown earlier.
 <input type="button" value="animate" (click)="animateDiv()" />          
  <div class="box"  [@divState]="state" >{{innerText}}</div>
Last Step :-
Now for the last step we would need an animate funtion to call on the click of the button. So, add the following to in your component class. This function only toggle between the state which actually triggers the animation.
1
2
3
4
5
6
7
8
9
animateDiv(){
            if(this.state == 'normal'){
                this.state = 'highlight';
                this.innerText = "Highlighted";
            }else{
                this.state = 'normal';
                this.innerText = "normal";
            }
        }
The above code displays how basic animation works, feel free to add your own css and play with it.
Read more at - http://www.oodlestechnologies.com/blogs/Animation-in-Angular-2

No comments:

Post a Comment