Nic*_*cky 9 javascript typescript angular4 angular
我有一个Directive可以放置元素来检查相关元素的当前滚动位置.
看起来像这样:
@Directive({
selector: '[my-scroll-animation]'
})
Run Code Online (Sandbox Code Playgroud)
每当位置满足某个阈值时,我希望元素使用动画显示在屏幕上.我知道,Component我可以附加animations属性以及属性中的一些设置host来激活动画.
我想要这样的东西:
import { myScrollAnimation } from './animations';
@Directive({
selector: '[my-scroll-animation]'
animations: [myScrollAnimation] // <- not possible?
})
Run Code Online (Sandbox Code Playgroud)
如何在指令中实现这一目标?
使用:Angular 4.0.0-rc.4
Tom*_*ula 13
Angular 4.2带来了很多动画改进.其中之一是AnimationBuilder,它允许编程动画构建.
您只需要在指令中注入AnimationBuilder,就可以将任何AnimationMetadata转换为工作动画.
@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 })),
];
}
}
Run Code Online (Sandbox Code Playgroud)
基于对beshashabatnoam答案中提到的问题的这种响应,我使用了一些解决方法。
指令实际上只是没有模板的组件。您可以使用属性选择器(例如:)[selector]并制作模板:来创建与指令具有相同功能的组件<ng-content></ng-content>。
结果,您可以创建一个“ foux-directive”组件,如下所示:
@Component({
selector: '[fadeInAnimation]',
animations: [
trigger('fadeIn', [
transition(':enter', [
style({opacity:'0'}),
animate(200, style({opacity:'1'}))
])
])
],
template: `<ng-content></ng-content>`,
})
export class FadeInDirective {
@HostBinding('@fadeIn') trigger = '';
}
Run Code Online (Sandbox Code Playgroud)
并像使用任何指令一样使用它:
<div fadeInAnimation> something I want to animate </div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6116 次 |
| 最近记录: |