Skip to content

Instantly share code, notes, and snippets.

@NathanWalker
Last active January 21, 2019 01:09
Show Gist options
  • Save NathanWalker/681a02fb307ac78e1b864e05395f2069 to your computer and use it in GitHub Desktop.
Save NathanWalker/681a02fb307ac78e1b864e05395f2069 to your computer and use it in GitHub Desktop.
NativeScript for Angular animate directive for silky smooth mobile (iOS/Android) animations anytime, anywhere and on anything.
/**
* Add this to your app's SharedModule declarations
*/
import { Directive, ElementRef, Input } from '@angular/core';
// nativescript
import { View } from 'tns-core-modules/ui/core/view';
import { Animation, AnimationDefinition } from 'tns-core-modules/ui/animation';
@Directive({
selector: '[animate]'
})
export class AnimateDirective {
@Input() animate: AnimationDefinition;
private _view: View;
private _animation: Animation;
private _viewInit = false;
constructor(private _el: ElementRef) { }
ngAfterViewInit() {
if (!this._viewInit) {
this._viewInit = true;
this._initAndPlay();
}
}
ngOnDestroy() {
this._cancel();
}
private _initAndPlay() {
if (!this._view && this._el && this._el.nativeElement) {
this._view = this._el.nativeElement;
}
if (this._view && this.animate) {
let animateOptions: AnimationDefinition = this.animate;
animateOptions.target = this._view;
this._animation = new Animation([animateOptions]);
this._play();
}
}
private _cancel() {
if (this._animation && this._animation.isPlaying) {
this._animation.cancel();
}
}
private _play() {
if (this._animation && !this._animation.isPlaying) {
this._animation.play().then(_ => {
// ignore
}, (err) => {
// ignore
// need this here to prevent:
// Unhandled Promise rejection: Animation cancelled. ; Zone: <root> ; Task: null ; Value: Error: Animation cancelled. _rejectAnimationFinishedPromise@file:///app/tns_modules/tns-core-modules/ui/animation/animation-common.js:98:31 [<root>]
});
}
}
}
/**
* Example usage:
* Now you can use it anywhere
*/
import { Component } from '@angular/core';
import { AnimationDefinition } from 'tns-core-modules/ui/animation';
@Component({
selector: 'app-some-component',
template: `
<StackLayout>
<Label class="fa" [text]="'fa-spinner' | fonticon" [animate]="animateOptions"></Label>
</StackLayout>
`
})
export class SomeComponent {
public animateOptions: AnimationDefinition = {
rotate: 360,
duration: 2500,
iterations: Number.POSITIVE_INFINITY
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment