12

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

Lucas
  • 9,871
  • 5
  • 42
  • 52
Naografix
  • 847
  • 2
  • 15
  • 35

1 Answers1

36

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

Lucas
  • 9,871
  • 5
  • 42
  • 52
  • is it possible to rotate image 4 sides? can you please show me how to do that. – U rock Jan 16 '18 at 13:24
  • u mean do a full rotation so that the image ends at starting position? – Lucas Jan 16 '18 at 13:28
  • 2
    simply change rotate(-180deg) to rotate(-360deg) . That will do a full rotation. If this answer helped you out please upvote :) – Lucas Jan 17 '18 at 14:26
  • Thank you for your answer but user can rotate unsteady images that we need about 4 states (90,180,270,360deg) something similar like https://stackoverflow.com/questions/16794310/rotate-image-with-javascript – U rock Jan 17 '18 at 17:34
  • How to save rotated image? – Loutocký May 17 '18 at 08:29