angularangular-animations

Angular animations - make div move right some amount on each click


How to, given div in angular animations, make it move right some amount (px) on each click? This is the demo of what I have in mind: https://jsfiddle.net/ergsLju1/23/

Same example in jQuery:

$('button').on('click', function() {
    $('div').animate({ left: '+=25px'  })
});

Solution

  • You could use Angular animations, but for this task the easiest way is to just use CSS transitions and property binding.

    import { CommonModule } from '@angular/common';
    import { Component } from '@angular/core';
    import { bootstrapApplication } from '@angular/platform-browser';
    import 'zone.js';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [CommonModule],
      template: `
    <button (click)="leftOffset = leftOffset + 25">Move</button>
    <div [ngStyle]="{'left': leftOffset + 'px'}">&nbsp;</div>`,
      styles: [
        `
    button {
      margin: 15px 0;
    }
    
    div {
      background-color: teal;
      width: 100px;
      height: 100px;
      position: relative;
      transition: left 200ms ease;
    }
    `,
      ],
    })
    export class App {
      leftOffset = 0;
    }
    
    bootstrapApplication(App);
    

    https://stackblitz.com/edit/stackblitz-starters-ukvd4c?file=src%2Fmain.ts