I have a Directive
I can put on elements that checks the current scroll position of the element in question.
Looks like this:
@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.
I would like something like this:
import { myScrollAnimation } from './animations';
@Directive({
selector: '[my-scroll-animation]'
animations: [myScrollAnimation] // <- not possible?
})
How can I achieve this in a Directive?
Using: Angular 4.0.0-rc.4
Angular 4.2 brought in a lot of animation improvements. One of them is AnimationBuilder, which allows for programmatic animation construction.
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 })),
];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With