Angular 2 - 如何在指令上设置动画? [英] Angular 2 - How to set animations on a Directive?

查看:139
本文介绍了Angular 2 - 如何在指令上设置动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指令我可以放置检查相关元素当前滚动位置的元素。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆