Angular animation : Rotation 180° click image

Naografix picture Naografix · Jun 2, 2017 · Viewed 16.9k times · Source

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

Answer

Lucas picture Lucas · Jun 2, 2017

EDITED check this stackblitz working example

import { ...} from '@angular/core';
import {trigger, state, style, animate, transition} from '@angular/animations';

@Component({
    selector: 'my-app',
    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('400ms ease-out')),
              transition('default => rotated', animate('400ms ease-in'))
        ]);
    ])
    ],
...

export class RotateComponent { 

    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:

[@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
  ],
  ...
})