Angular: How can I apply animation to rotate an image within a component?

Within my map application, I have implemented a component called compass component. I am seeking a way to programmatically rotate this compass with animation as the map is rotated. The solution involves utilizing angular animation.

To achieve this functionality, I have imported various elements from '@angular/core' and 'util.service'. The component itself includes animations for the rotation of the compass based on specific states and transitions.

@Component({
  selector: "app-compasstool",
  template: require("./compasstool.component.html"),
  styles: [require("./compasstool.component.scss")],

  animations: [
    trigger('flyInOut', [
      state('start', style({ transform: 'rotate(0rad)' })),
      state('end', style({ transform: 'rotate(0.9rad)' })),
      transition('* => start', [
        animate("5s", keyframes([
          style({ transform: 'rotate(0rad)' }),// offset = 0         
        ]))
      ]),
      transition('* => end', [
        animate("2s", keyframes([
          style({ transform: 'rotate(0rad)' }),// offset = 0
          style({ transform: 'rotate(0.2rad)' }), // offset = 0.33
          style({ transform: 'rotate(0.6rad)' }), // offset = 0.66
          style({ transform: 'rotate(0.9rad)' }) // offset = 1
        ]))
      ]),
    ]),
  ],
})

The challenge lies in invoking the animation along with the rotation inside the component when map rotation values are provided in radians. Additionally, it's important to note that the animation only triggers at the initial setup of the component.

Answer №1

For a dynamic rotation where the animation is based on rotation properties in radians, consider utilizing AnimationBuilder.

Check out this demo showcasing the rotation of a .needle element using AnimationBuilder: https://stackblitz.com/edit/angular-animation-builder-pl9qko

This example demonstrates how AnimationBuilder creates an AnimationPlayer to handle rotations based on radians.

  animationFactory = this.animationBuilder
    .build([
      style({ transform: `rotate(${this.lastRadians}rad)` }),
      animate(200, style({ transform: `rotate(${this.radians}rad)` }))
    ]);

Answer №2

The code snippet for your component.ts is shown below:

@Component({
  selector: "app-compasstool",
  template: require("./compasstool.component.html"),
  styles: [require("./compasstool.component.scss")],
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(-360deg)' })),
            transition('rotated => default', animate('2000ms ease-out')),
            transition('default => rotated', animate('2000ms ease-in'))
        ])
    ]
})
export class AppComponent {

    state: string = 'default';

    rotate() {
        this.state = (this.state === 'default' ? 'rotated' : 'default');
    }

}

Now, in your component.html file, include the following:

<h1>Angular image rotation example</h1>
<button (click)="rotate()">Press me to rotate</button>

<hr>
<br><br><br><br>

<!-- Ensure to add binding to tag -->
<img [@rotatedState]='state' src="https://images-na.ssl-images-amazon.com/images/I/513hBIizJUL._SY355_.jpg" >

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can the `ng new --collection` command be utilized in Angular?

Can you explain the purpose of using the ng new --collection command in Angular? And can you provide instructions on how to use it in the command prompt? If you have any knowledge about this, please share with me. ...

What could be causing the issue: Unable to locate or read the file: ./styles-variables?

I'm currently following a tutorial on how to create responsive layouts with Bootstrap 4 and Angular 6. You can find the tutorial here. I've reached a point where I need to import styles-variables.scss in my styles file, but I keep encountering t ...

Tips for customizing a generic repository error message

I have a GenericRepository class that provides basic functionality for interacting with persistence storage such as creating, finding, getting all, deleting, and updating data. Within the find method, I am searching the database using its primary key. If ...

Angular Route seems unreachable

These are my guidelines for routes: export const appRoutes: Routes = [ { path: "", component: HomeComponent }, { path: '/signup', component: AppComponent }, { path: "**", redirectTo: "/" } ]; Upon attempting to access the URL: http ...

When triggering the event: Was anticipating a spy, however received a Function instead

Upon running my test, I encountered the following error message: Error: Unhandled Promise rejection: <toHaveBeenCalledWith> : Expected a spy, but received Function. it('should change the value of myComponent', () => { spyOn(component ...

Verify if the page was generated as a regular Page or a modal page

Within the UpgradePage, I have a scenario where I want to navigate to the same page either through the side menu or as a modal page using push/setRoot. Q: The method upgradeLater() is where I need to make a decision on whether to redirect to another page, ...

Angular 6: Prevented Loading Resource Due to Content Security Policy: A script from self was blocked from being loaded on the page

Currently, I am developing a project in Angular 6 and everything seems to be running smoothly. Running the command ng --serve and building it using ng build results in no errors when deploying it on my local Tomcat Server. However, when attemptin ...

Which Angular2 npm packages should I be installing?

When I'm trying to create an empty app without using angular-cli, it's really difficult for me to figure out which packages or libraries to include. Searching for angular2 on npmjs yields unwanted results, forcing me to click through multiple li ...

synchronize the exchange of information and events between two components

Just joined this platform and diving into Angular 7 coding, but already facing an issue. I've set up two components along with a service. The data is fetched by the service upon clicking a button in the searchbar component, and I aim to display it i ...

Enhance user information by adding necessary fields

I often encounter situations where I need to select a specific entry from a set of data in a component, whether through a select box or as part of a table. However, the way I intend to utilize this data typically requires additional fields like the "label ...

Every instance of 'WeakMap' must include the same type parameters

While developing an Ionic App, I encountered a strange issue. Everything was running smoothly until I cloned the source code to a different machine, which resulted in an error that is displayed in the attached image. Even though there are no compilation e ...

Angular: Creating an instance of a class with StaticProvider passed as a parameter

Having trouble instantiating a class with a StaticProvider. Here's the code snippet: main.ts export function createProvider() { // some implementation return result; // result is a string } const providers = [ { provide: 'TEST' ...

Sometimes the PDF does not display even though the iframe src attribute is updating in Angular 6

I have encountered an issue with displaying a PDF file in my code. Sometimes the PDF shows up correctly, but other times it fails to load. I even tried using an iFrame instead of embed but faced the same scenario. Can anyone provide assistance? Here is my ...

Conceal certain components when a user is authenticated

Below is the content of my app.component.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class='container'> <ul class="nav navbar-nav"> <li class='nav-item'> <a clas ...

mat-slider: experiencing delay in updating while dragging it

Incorporating @angular/material in my Angular 5 application has been quite the journey. The specific version of Angular Material that I have implemented is 5.0.2, along with @angular/animations 5.1.2. My usage of the slider component is rather straightfor ...

I'm wondering why my JWT token appears as null on the backend while it is not null on the frontend

I'm having trouble with a GET request to my mLab database. I included a JWT token in the request and verified it on both the client and server side. Strangely, it appears correctly on the client but as null on the server. Any assistance on this matter ...

Tips for decreasing the size of your Angular 7 production build

What are the best practices to minimize production build size? For production build, use the command ng build --prod To configure angular.json file, refer to the following links: https://i.stack.imgur.com/3LSxZ.jpg https://i.stack.imgur.com/yE0fL.jpg ...

When using Angular Reactive Forms with a number type control, the form will trigger a re-render when the

My Angular(v7) Reactive Form (or template-only form) is experiencing issues with re-rendering and validation on blur when using an <input> with type="number". The error feedback <div> next to the input contains a value suggestion button, whic ...

Unable to identify the versions of "@angular/cli" as the local installation seems to be faulty

My local installation broke after installing the Momento plugin. This plugin caused issues. When I try running my project with the command ng serve, I get this error message: Cannot determine versions of "@angular/cli". This likely means your local ...

Transmitting Filter Choices as an Object for Retrieving Multiple Values within an Angular Application

In my Angular application, I have a function that takes user selections for various filter types and sends a request to the API to retrieve filtered data based on those selections. Each filter type returns values in an array format, allowing users to selec ...