Cómo crear animaciones reutilizables en Angular 2
Estoy jugando con la API de animación, y me gustaría crear una animación reutilizable como decir deslizamiento en el contenido para vistas de enrutador de nivel superior. Me las arreglé para obtener a través de la sintaxis de metadatos funky (que en realidad es bastante genial una vez que pase la loca idea de usar metadatos) para obtener las animaciones en su mayoría trabajando.
@Component({
//moduleId: module.id,
selector: 'album-display',
templateUrl: './albumDisplay.html',
animations: [
trigger('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';
...
}
Y luego asignarlo a mi elemento de nivel superior en el componente:
<div class="container" [@slideIn]="slideInState">
Así que esto funciona, pero ¿cómo puedo hacer esto reutilizable? No quiero pegar este meta datos en cada vista. Dado que se trata de metadatos no estoy seguro de cómo podría hacer esto reutilizable.
5 answers
Una forma posible es poner el código del disparador de animación en un archivo separado y exportarlo como variable const
y usarlo en el componente como se muestra a continuación.
Animaciones.ts
import { trigger, state, style, transition, animate } from '@angular/core';
export const slideIn = trigger('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 (en inglés).componente.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';
...
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-31 07:08:03
Tal vez es un poco tarde, pero todavía me gustaría poner una respuesta para una versión más dinámica del disparador.
Ponga el código de activación de la animación en un archivo separado y expórtelo como function
.
Traduce.ts
import { AnimationEntryMetadata, trigger, state, style, transition, animate } from '@angular/core';
export function TranslateX( name: string, x: string, duration: number ): AnimationEntryMetadata {
return trigger( 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')),
]);
}
Por lo tanto, en el componente aplicación.componente.ts
import { TranslateX } from './translate';
@Component({
...
templateUrl: './app.component.html',
animations: [
TranslateX( 'trigger1Title','-100%', 200 ),
TranslateX( 'trigger2Title','20vw', 700 )
]
...
})
Y en la plantilla app.componente.html
...
<div [@trigger1Title]="token1"> ... </div>
<div [@trigger2Title]="token2"> ... </div>
...
Puede personalizar el desencadenador con más datos de entrada, por ejemplo, separando los tiempos de transición, etc.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-29 11:38:09
La solución adecuada sería tener animaciones soportadas en Directivas.
No es el caso, pero hay un problema para eso en el Github de Angular: https://github.com/angular/angular/issues/9947
Espero que se resuelva pronto.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-25 18:03:25
Con una clase y se puede extender,
import { trigger, style, state, animate, transition, AnimationMetadata } from "@angular/core";
export class MyAwesomeAnimations {
/**
*
* @param nameTrigger Name of triggers
* @param setNewsStates add states for animations
* @param setNewTransitions add transitions for states
*/
SetTrigger(nameTrigger: string, 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 trigger(nameTrigger, metaData);
}
}
Para uso
@Component({
selector: "orden-detail-component",
animations: [new MyAwesomeAnimations().SetTrigger("slideIn")],
template:"<div class="container" [@slideIn]="slideInState">"
})
export class OrdenDetailComponent {
slideInState = 'in';
}
Espero que de esa manera pueda ayudarte
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-27 02:11:13
Ejemplo de animación de enrutador en Angular 4
Acabo de terminar de abordar las animaciones del enrutador yo mismo usando Angular 4, aquí hay un par de animaciones de ejemplo que se me ocurrió para una transición de desvanecimiento y transición de entrada/salida.
Echa un vistazo este post para más detalles y una demostración en vivo.
Angular 4 Animación de entrada/salida de diapositivas
// import the required animation functions from the angular animations module
import { trigger, state, animate, transition, style } from '@angular/animations';
export const slideInOutAnimation =
// trigger name for attaching this animation to an element using the [@triggerName] syntax
trigger('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 { trigger, state, animate, transition, style } from '@angular/animations';
export const fadeInAnimation =
// trigger name for attaching this animation to an element using the [@triggerName] syntax
trigger('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 }))
]),
]);
Componente con transición adjunto
import { Component } from '@angular/core';
// import fade in animation
import { fadeInAnimation } from '../_animations/index';
@Component({
moduleId: module.id.toString(),
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 {
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-22 05:44:58