Search code examples
htmlangularangular-animations

Angular animation : Rotation 180° click image


How to make a image rotation (click : 0° -> 180° / click again : 180° -> 0°) on image button with Angular 4 ?

I use Angular Material too.

This is my button :

 <!-- Button open left menubar -->
<button md-icon-button class="left-menubar-button"  (click)="start.toggle()">
  <md-icon class="md-custom-theme-gray">label_outline</md-icon>
</button>

This button will open a sidenav, and I want to animate it to get more userfriendly

Thanks


Solution

  • You do not need material as Angular brings built in animations. Here goes an example:

    import { Component } from '@angular/core';
    import { trigger, state, style, animate, transition } from '@angular/animations';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
      animations: [
          // Each unique animation requires its own trigger. The first argument of the trigger function is the name
          trigger('rotatedState', [
            state('default', style({ transform: 'rotate(0)' })),
            state('rotated', style({ transform: 'rotate(-180deg)' })),
            transition('rotated => default', animate('1500ms ease-out')),
            transition('default => rotated', animate('400ms ease-in'))
          ])
      ]
    })
    
    export class AppComponent {
        state: string = 'default';
        rotate() {
            this.state = (this.state === 'default' ? 'rotated' : 'default');
        }
    }
        
    

    And in template:

    <button (click)="rotate()">Press me to rotate</button>
    

    And make sure to add binding to tag you are operating on:

    <img [@rotatedState]='state' />
    

    In addition make sure you import the animation module to your app like so:

    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    
    @NgModule({
      ...,
      imports: [
        ...,
        BrowserAnimationsModule
      ],
      ...
    })
    

    Check stackblitz with working example