Comment créez-vous des animations réutilisables dans Angular 2?

Je joue avec l’API Animation, et j’aimerais créer une animation réutilisable telle que le glissement de contenu pour les vues de routeur de haut niveau. J’ai réussi à passer à travers la syntaxe des métadonnées géniales (qui est en fait plutôt cool une fois passé l’idée folle d’utiliser des métadonnées) pour que les animations fonctionnent principalement.

@Component({ //moduleId: module.id, selector: 'album-display', templateUrl: './albumDisplay.html', animations: [ sortinggger('slideIn', [ state('*', style({ transform: 'translateX(100%)', })), state('in', style({ transform: 'translateX(0)', })), state('out', style({ transform: 'translateX(-100%)', })), transition('* => in', animate('600ms ease-in')), transition('in => out', animate('600ms ease-in')) ]) ] }) export class AlbumDisplay implements OnInit { slideInState = 'in'; ... } 

Et puis atsortingbuer cela à mon élément de premier niveau dans le composant:

  

Cela fonctionne donc, mais comment puis-je le rendre réutilisable? Je ne veux pas coller ces métadonnées sur chaque vue. Comme il s’agit de métadonnées, je ne suis pas sûr de savoir comment vous pourriez rendre cela réutilisable.

Un moyen possible est de placer le code de déclenchement de l’animation dans un fichier séparé et de l’exporter en tant que variable const et de l’utiliser dans le composant ci-dessous.

animations.ts

 import { sortinggger, state, style, transition, animate } from '@angular/core'; export const slideIn = sortinggger('slideIn', [ state('*', style({ transform: 'translateX(100%)', })), state('in', style({ transform: 'translateX(0)', })), state('out', style({ transform: 'translateX(-100%)', })), transition('* => in', animate('600ms ease-in')), transition('in => out', animate('600ms ease-in')) ]); 

album-display.component.ts

 import { slideIn } from './animations'; // path to your animations.ts file @Component({ //moduleId: module.id, selector: 'album-display', templateUrl: './albumDisplay.html', animations: [ slideIn ] }) export class AlbumDisplay implements OnInit { slideInState = 'in'; ... } 

Peut-être que c’est un peu tard, mais j’aimerais quand même répondre à une version plus dynamic du déclencheur.

Placez le code de déclenchement de l’animation dans un fichier séparé et exportez-le en tant que function .

translate.ts

 import { AnimationEntryMetadata, sortinggger, state, style, transition, animate } from '@angular/core'; export function TranslateX( name: ssortingng, x: ssortingng, duration: number ): AnimationEntryMetadata { return sortinggger( name, [ state('false', style({ transform: 'translateX(0)' }) ), state('true', style({ transform: 'translateX(' + x + ')' }) ), transition('0 => 1', animate( duration + 'ms ease-in')), transition('1 => 0', animate( duration + 'ms ease-out')), ]); } 

donc, dans le composant app.component.ts

 import { TranslateX } from './translate'; @Component({ ... templateUrl: './app.component.html', animations: [ TranslateX( 'sortinggger1Title','-100%', 200 ), TranslateX( 'sortinggger2Title','20vw', 700 ) ] ... }) 

et dans le modèle app.component.html

 ... 
...
...
...

Vous pouvez personnaliser le déclencheur avec davantage de données d’entrée, par exemple en séparant les temps de transition, etc.

Une solution appropriée serait d’avoir des animations sockets en charge dans les directives.

Ce n’est pas le cas, mais il y a un problème pour cela sur le Github d’Angular: https://github.com/angular/angular/issues/9947

J’espère que cela sera bientôt résolu.

Avec une classe et vous pouvez prolonger,

 import { sortinggger, style, state, animate, transition, AnimationMetadata } from "@angular/core"; export class MyAwesomeAnimations { /** * * @param nameTrigger Name of sortingggers * @param setNewsStates add states for animations * @param setNewTransitions add transitions for states */ SetTrigger(nameTrigger: ssortingng, setNewsStates?: AnimationMetadata[], setNewTransitions?: AnimationMetadata[]): any { let metaData: AnimationMetadata[] = [ state('*', style({ transform: 'translateX(100%)', })), state('in', style({ transform: 'translateX(0)', })), state('out', style({ transform: 'translateX(-100%)', })), transition('* => in', animate('600ms ease-in')), transition('in => out', animate('600ms ease-in')) ]; if (setNewsStates) metaData.concat(setNewsStates); if (setNewTransitions) metaData.concat(setNewTransitions); return sortinggger(nameTrigger, metaData); } } 

Pour utilisation

  @Component({ selector: "orden-detail-component", animations: [new MyAwesomeAnimations().SetTrigger("slideIn")], template:"
" }) export class OrdenDetailComponent { slideInState = 'in'; }

J’espère que cette façon peut vous aider

Exemple d’animation de routeur dans Angular 4

Je viens de finir de m’attaquer aux animations du routeur avec Angular 4, voici quelques exemples d’animations que j’ai créées pour une transition en fondu et une transition in / out.

Consultez ce post pour plus de détails et une démo en direct.

Angular 4 Animation d’animation in / out

 // import the required animation functions from the angular animations module import { sortinggger, state, animate, transition, style } from '@angular/animations'; export const slideInOutAnimation =    // sortinggger name for attaching this animation to an element using the [@sortingggerName] syntax    sortinggger('slideInOutAnimation', [        // end state styles for route container (host)        state('*', style({            // the view covers the whole screen with a semi tranparent background            position: 'fixed',            top: 0,            left: 0,            right: 0,            bottom: 0,            backgroundColor: 'rgba(0, 0, 0, 0.8)'        })),        // route 'enter' transition        transition(':enter', [            // styles at start of transition            style({                // start with the content positioned off the right of the screen,                // -400% is required instead of -100% because the negative position adds to the width of the element                right: '-400%',                // start with background opacity set to 0 (invisible)                backgroundColor: 'rgba(0, 0, 0, 0)'            }),            // animation and styles at end of transition            animate('.5s ease-in-out', style({                // transition the right position to 0 which slides the content into view                right: 0,                // transition the background opacity to 0.8 to fade it in                backgroundColor: 'rgba(0, 0, 0, 0.8)'            }))        ]),        // route 'leave' transition        transition(':leave', [            // animation and styles at end of transition            animate('.5s ease-in-out', style({                // transition the right position to -400% which slides the content out of view                right: '-400%',                // transition the background opacity to 0 to fade it out                backgroundColor: 'rgba(0, 0, 0, 0)'            }))        ])    ]); 

Angular 4 Fade in animation

 // import the required animation functions from the angular animations module import { sortinggger, state, animate, transition, style } from '@angular/animations'; export const fadeInAnimation =    // sortinggger name for attaching this animation to an element using the [@sortingggerName] syntax    sortinggger('fadeInAnimation', [        // route 'enter' transition        transition(':enter', [            // css styles at start of transition            style({ opacity: 0 }),            // animation and styles at end of transition            animate('.3s', style({ opacity: 1 }))        ]),    ]); 

Composant avec transition attachée

 import { Component } from '@angular/core'; // import fade in animation import { fadeInAnimation } from '../_animations/index'; @Component({    moduleId: module.id.toSsortingng(),    templateUrl: 'home.component.html',    // make fade in animation available to this component    animations: [fadeInAnimation],    // attach the fade in animation to the host (root) element of this component    host: { '[@fadeInAnimation]': '' } }) export class HomeComponent { }