开始了。适合微小的动画。
我直接使用AnimationPlayer + AnimationBuilder => 无需人为地向前切换状态 + 向后触发动画。受此片段启发并进一步简化。
import { Directive, Input, HostListener } from '@angular/core';
import { ElementRef } from '@angular/core';
import {
AnimationPlayer,
AnimationBuilder
} from '@angular/animations';
@Directive({
selector: '[clickAnimation]',
})
export class ClickAnimationDirective {
private player: AnimationPlayer;
@Input() clickAnimation: any;
@HostListener('click', ['$event'])
onClick() {
// sanitize just in case
if (this.player) { this.player.destroy(); }
const factory = this.builder.build(this.clickAnimation);
const player = factory.create(this.el.nativeElement);
// ensure back-to-original
player.onDone(() => { player.reset(); });
player.play();
}
constructor(private builder: AnimationBuilder, private el: ElementRef) { }
}
在您的模板中:
<app-button
[clickAnimation]="trafficLight"
...
在您的组件类中:
public trafficLight: AnimationMetadata[] = [
style({ borderColor: 'red' }),
animate('400ms ease-in', style({ borderColor: 'yellow' })),
animate('400ms ease-in', style({ borderColor: 'cyan' })),
//alternative way to ensure back to original
// animate('400ms ease-in', style({ borderColor: '*' })),
];