5

I have image and two buttons that should rotate that image 45 or -45 degrees.

<div>
    <img src="/assets/img1.png">
</div>
<div>
    <button type="submit">rotate left 45</button>
    <button type="submit">rotate right 45</button>
</div>

How can I make function that will apply css transform rotate to this image? Steps should be in 45deg ether way and it should constantly rotate no matter how many times user click on button.

John Theoden
  • 325
  • 2
  • 10
  • 23
  • You could use (#) on tag (reference) and then create a function (in the .ts) to apply the css style. Or use the animation provided by angular. Read the doc.. – Izio May 14 '18 at 15:24
  • As a starter, you can use CSS to rotate the image like so: `transform: rotate(45deg);` – Flink May 14 '18 at 15:30

1 Answers1

10

You could update the elements CSS transform property on click.

let rotationAmount = 0;

function rotateImage(direction) {
  rotationAmount += direction == 'left' ? -45 : 45;
  
  document.querySelector('#image').style.transform = `rotate(${rotationAmount}deg)`;
}
#image {
  height: 100px;
  width: 100px;
}

.button-wrapper {
  margin-top: 30px;
}
<div>
    <img id="image" src="">
</div>
<div class="button-wrapper">
    <button type="submit" onclick="rotateImage('left')">rotate left 45</button>
    <button type="submit" onclick="rotateImage('right')">rotate right 45</button>
</div>
Josh
  • 1,455
  • 19
  • 33
  • Could you do some correction to work with angular 2+ ? :) – John Theoden May 14 '18 at 16:23
  • Or perhaps ...how can I do document.querySelector('#image').style.transform = 'rotate(' + rotationAmount + 'deg)'; with angular 2+? – John Theoden May 14 '18 at 16:38
  • This is nice but there's a con here, you are directly accessing the DOM which is not a good practice so instead use Renderer2, just replace your line of code "document.querySelector('#image').style.transform = `rotate(${rotationAmount}deg)`;" with " document.querySelector('#image').style.transform = `rotate(${rotationAmount}deg)`;" and do not forget to import Renderer2 from @angular/core and instantiate it in constructor – Alekya Mar 19 '20 at 07:59