Repeat animation angular 4

2020-03-02 05:12发布

I created the following animation:

fade.animation.ts:

import { Component } from '@angular/core';
import { trigger, state, animate, query, transition, style, stagger } from 
'@angular/animations';
export let fade = trigger('fade', [
   state('void', style({ opacity: 0 })),
   transition(':enter, :leave', [
    animate(2000)
   ])
]);

I'm using in the next component:

 <div id="mpl_loader" class="divCabeceraTitulo">
        <div class="lineaTitulo">
            <div class="logoMinisterio" [@fade]>
                <img src="assets/imagenes/SRDLOGO.png">
            </div> 
            <div class="logoGesRepro">
               <img  class="imgGesRepro" src="assets/imagenes/gesReproB.png">
            </div>           
            <div class="descripcionAplicacion">
                <span>título</span>
            </div>
        </div>
  </div>

The animation works, the problem is that it only runs once, when it loads the component, what I want is for it to do it "n" times. How do I it? Please help

2条回答
冷血范
2楼-- · 2020-03-02 05:25

A way to do it would be to use two states, that you would toggle, at the end of the previous animation, and this for as many time as you have defined.

animations.ts

import { Component } from '@angular/core';
import { trigger, state, animate, query, transition, style, stagger } from 
'@angular/animations';
export const fade = trigger('fade', [
   state('inactive', style({ opacity: 0 })),
   state('active', style({ opacity: 1 })),
   transition('* <=> *', [
    animate(2000)
   ])
]);

app.component.html

Here is the important part : [@fade]="state" **(@fade.done)**="onDone($event)"

<div id="mpl_loader" class="divCabeceraTitulo">
        <div class="lineaTitulo">
            <div class="logoMinisterio" [@fade]="state" (@fade.done)="onDone($event)">
                <img src="assets/imagenes/SRDLOGO.png">
            </div> 
            <div class="logoGesRepro">
               <img  class="imgGesRepro" src="assets/imagenes/gesReproB.png">
            </div>           
            <div class="descripcionAplicacion">
                <span>título</span>
            </div>
        </div>
  </div>

app.component.ts

Finally, you increment the counter and toggle the state at the end of the previous animation :

@Component({
  ...
  animations: [fade]
})
export class AppComponent {
  times = 5;
  counter = 0;

  onDone($event) {
    // call this function at the end of the previous animation.
    // run it as many time as defined
    if (this.counter < this.times) {
      this.state = this.state === 'active' ? 'inactive' : 'active';
      this.counter++;
    }
  }
}

Here is a StackBlitz example I created for this : https://angular-wekm96.stackblitz.io

(I applied the animation on the text)

查看更多
祖国的老花朵
3楼-- · 2020-03-02 05:29

Use keyframes with animation-iteration-count (configures the number of times the animation should repeat)

查看更多
登录 后发表回答