Angular Animate Fade-In,淡出组件

时间:2017-11-01 17:41:14

标签: javascript angular ng-animate

我有以下代码,我想在进入和离开时应用于组件:

animations: [
    trigger('visibilityChanged', [
      state('in', style({opacity: 1})),
      transition('void => *', [
        style({opacity: 1}),
        animate(100)
      ]),
      transition('* => void', [
        animate(100, style({opacity: 0}))
      ])
    ])
  ]

这几乎与Angular docs provide的示例完全相同,但由于某种原因,当从void => *状态开始时,没有淡入。

我也在live examples页面尝试过此操作但没有成功。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

 animations: [
  trigger('visibilityChanged', [
    state('in', style({
      opacity: 0
    })),
    state('out',   style({
      opacity: 1
    })),
    transition('in => out', animate('100ms ease-in')),
    transition('out => in', animate('100ms ease-out'))
  ])
]

答案 1 :(得分:0)

我建议您结帐 ng-animate ,因为它具有许多开箱即用的动画,这些动画很容易实现,但是如果想要的代码没有适合您目的的库,请使用以下代码:

import { trigger, animate, transition, style, state } from '@angular/animations';

export const simpleFadeAnimation = trigger('simpleFadeAnimation', [

    // the "in" style determines the "resting" state of the element when it is visible.
    state('in', style({opacity: 1})),

    // fade in when created. this could also be written as transition('void => *')
    transition(':enter', [
      style({opacity: 0}),
      animate(1000 )
    ]),

    // fade out when destroyed. this could also be written as transition('void => *')
    transition(':leave',
      animate(1000, style({opacity: 0})))
]);

或者如果要通过“ X”轴进行平移,请使用以下方法:

import { trigger, animate, transition, style, group, query } from '@angular/animations';

export const slideInAnimation = trigger('slideInAnimation', [
   // Transition between any two states
   transition('* <=> *', [
   // Events to apply
   // Defined style and animation function to apply
   // Config object with optional set to true to handle when element not yet added to the DOM
  query(':enter, :leave', style({ position: 'fixed', width: '100%', zIndex: 2 }), { optional: true }),
    // group block executes in parallel
    group([
      query(':enter', [
        style({ transform: 'translateX(100%)' }),
        animate('0.7s ease-out', style({ transform: 'translateX(0%)' }))
      ], { optional: true }),
      query(':leave', [
        style({ transform: 'translateX(0%)' }),
        animate('0.7s ease-out', style({ transform: 'translateX(-100%)' }))
       ], { optional: true })
    ])
  ])
]);

之后,您需要将其导入到 .ts 文件中的 @Component 装饰器中。而且,如果您想通过应用程序内部的所有组件共享它,请使用以下命令:

<div [@slideInAnimation]="o.isActivated ? o.activatedRoute : ''">
    <router-outlet #o="outlet"></router-outlet>
</div>