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
  • 8,920
  • 5
  • 39
  • 49
Naografix
  • 755
  • 1
  • 11
  • 32

1 Answers1

31

You do not need material as Angular brings built in animations in its core module. Here goes an 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 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
  • 8,920
  • 5
  • 39
  • 49
  • 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
  • hey @Loutocký remember that you would have to rotate the image again on server side and then save it.... I think you need to ask a new question with your server language and ask how to rotate it before saving it..... – Lucas May 18 '18 at 21:07