Abhijit Chakra
Abhijit Chakra

Reputation: 3236

How to iterate an animation infinitely in Angular

I want to iterate animation infinitely and stop and start in my component. I have written the below code:

@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
  animations: [
    // Each unique animation requires its own trigger. The first argument of the trigger function is the name
    trigger('run', [transition('void => *',[animate(1000, keyframes([
      style({transform: 'translateX(0)    rotateY(0)',        offset: 0}),
      style({transform: 'translateX(10%)  rotateY(70deg)',    offset: 0.33}),
      style({transform: 'translateX(20%) rotateY(30deg)',   offset: 0.66}),
      style({transform: 'translateX(0%)',                  offset: 1.0})
    ]))
    ])  
  ])  
]
}) 

In the HTML file I have written below code:

<img  @run id="animicon" src="assets/.../logo_1.png" style="background:black" class="image--background">

Upvotes: 1

Views: 3156

Answers (1)

Vega
Vega

Reputation: 28738

Using Angular animations would be incorrect in this context. They are intended to be used when the component is added via router or *ngIf or programmatically, when the regular/plain CSS cannot be used or wont work.
Adding them would only make your code unnecessarily complexe, even slow.
For the case you described in your post, you don't need an Angular animation, plain css animation is plenty enough:

CSS

@keyframes myAnimation {
  0%   {transform: translateX(0) rotateY(0)}
  33%  {transform: translateX(10%) rotateY(70deg)}
  66%  {transform: translateX(20%) rotateY(30deg)}
  100% {transform: translateX(0%)}
}

img {
  animation: myAnimation 5s infinite;
}

Demo


However, if you still want to use Angular approach, here is a take.

ts:

.....
animations: [
    // Each unique animation requires its own trigger. The first argument of the trigger function is the name
    trigger('run', [
      transition('* => *', [
        animate(
          1000,
          keyframes([
            style({ transform: 'translateX(0)    rotateY(0)', offset: 0 }),
            style({
              transform: 'translateX(10%)  rotateY(70deg)',
              offset: 0.33,
            }),
            style({
              transform: 'translateX(20%) rotateY(30deg)',
              offset: 0.66,
            }),
            style({ transform: 'translateX(0%)', offset: 1.0 }),
          ])
        ),
      ]),
    ]),
  ],

  ....
  trigger: boolean;

  ngOnInit() {
    setInterval(() => (this.trigger = !this.trigger),1000);
  }

HTML:

<img
  [@run]="trigger"
  .....
/>

demo

Upvotes: 11

Related Questions