Last active
December 21, 2018 14:17
-
-
Save deebloo/91c7721721f9cd8cbe0922ee3b21d73e to your computer and use it in GitHub Desktop.
custom directive that creates and destroys elements with an enter and exit animation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Directive, TemplateRef, ViewContainerRef, Input, Renderer2 } from '@angular/core'; | |
| import { timer } from 'rxjs'; | |
| @Directive({ | |
| selector: '[ifAnimation]' | |
| }) | |
| export class IfAnimationDirective { | |
| @Input() lsIfAnimationDelay: number; | |
| @Input() set lsIfAnimation(display: boolean) { | |
| if (display) { | |
| if (this.lsIfAnimationDelay) { | |
| timer(this.lsIfAnimationDelay).subscribe(() => { | |
| this.containerRef.createEmbeddedView(this.templateRef); | |
| this.triggerAnimation(this.templateValue, this.enterAnimationClass); | |
| }); | |
| } else { | |
| this.containerRef.createEmbeddedView(this.templateRef); | |
| this.triggerAnimation(this.templateValue, this.enterAnimationClass); | |
| } | |
| } else { | |
| if (this.templateValue) { | |
| this.triggerAnimation(this.templateValue, this.exitAnimationClass).then(() => { | |
| this.containerRef.clear(); | |
| }); | |
| } | |
| } | |
| } | |
| private get templateValue(): HTMLElement { | |
| return this.templateRef.elementRef.nativeElement.nextElementSibling; | |
| } | |
| private get enterAnimationClass() { | |
| if (this.templateValue) { | |
| return this.templateValue.getAttribute('enter') || 'opening'; | |
| } | |
| return 'opening'; | |
| } | |
| private get exitAnimationClass() { | |
| if (this.templateValue) { | |
| return this.templateValue.getAttribute('exit') || 'closing'; | |
| } | |
| return 'closing'; | |
| } | |
| constructor( | |
| private templateRef: TemplateRef<any>, | |
| private containerRef: ViewContainerRef, | |
| private renderer: Renderer2 | |
| ) {} | |
| private triggerAnimation(el: HTMLElement, animation: string): Promise<void> { | |
| return new Promise(resolve => { | |
| const listener = this.renderer.listen(el, 'animationend', () => { | |
| this.renderer.removeClass(el, animation); | |
| listener(); | |
| resolve(); | |
| }); | |
| this.renderer.addClass(el, animation); | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment