Angular 2 - 如何在指令上设置动画? [英] Angular 2 - How to set animations on a Directive?
问题描述
我有一个指令
我可以放置检查相关元素当前滚动位置的元素。
I have a Directive
I can put on elements that checks the current scroll position of the element in question.
看起来像这样:
@Directive({
selector: '[my-scroll-animation]'
})
每当该位置满足某个阈值时,我希望该元素出现在屏幕上使用动画。我知道对于组件
我可以附加动画
属性以及中的一些设置主机
属性以激活动画。
Whenever the position satifies a certain treshold, I want the element to appear on screen using an animation. I know that for a Component
I can attach an animations
property along with some settings in the host
property to activate the animation.
我想这样的事情:
import { myScrollAnimation } from './animations';
@Directive({
selector: '[my-scroll-animation]'
animations: [myScrollAnimation] // <- not possible?
})
如何在指令中实现这一目标?
How can I achieve this in a Directive?
使用:Angular 4.0.0-rc.4
Using: Angular 4.0.0-rc.4
推荐答案
Angular 4.2带来了很多动画改进。其中之一是AnimationBuilder,它允许编程动画构建。
Angular 4.2 brought in a lot of animation improvements. One of them is AnimationBuilder, which allows for programmatic animation construction.
您只需要在指令中注入AnimationBuilder,就可以将任何AnimationMetadata转换为工作动画。
You just need to inject AnimationBuilder in your directive, and you can turn any AnimationMetadata into working animation.
@Directive({
selector: '[zetFadeInOut]',
})
export class FadeInOutDirective {
player: AnimationPlayer;
@Input()
set show(show: boolean) {
if (this.player) {
this.player.destroy();
}
const metadata = show ? this.fadeIn() : this.fadeOut();
const factory = this.builder.build(metadata);
const player = factory.create(this.el.nativeElement);
player.play();
}
constructor(private builder: AnimationBuilder, private el: ElementRef) {}
private fadeIn(): AnimationMetadata[] {
return [
style({ opacity: 0 }),
animate('400ms ease-in', style({ opacity: 1 })),
];
}
private fadeOut(): AnimationMetadata[] {
return [
style({ opacity: '*' }),
animate('400ms ease-in', style({ opacity: 0 })),
];
}
}
- 示例存储库
- Angular 4.2+中的新一波动画功能 / li>
- Example repository
- A New Wave of Animation Features in Angular 4.2+
这篇关于Angular 2 - 如何在指令上设置动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!