如何在Angular2中为路由组件使用动画

3

我希望在活动路由链接改变时能够对组件进行淡入淡出的动画。我该如何编写动画代码,以便当路由器发生更改时,一个组件淡出,然后另一个组件淡入?

我一直试用的代码如下所示。

@Component({
  selector: 'app-component',
  templateUrl: './component.component.html',
  animations: [trigger(
    'openClose',
    [
      transition(":enter", [
        style({ opacity: 0 }),
        animate('2000ms', style({ opacity: 1 }))
      ]),
      transition(":leave", [
        animate('2000ms', style({ opacity: 0 }))
      ])
    ])]
})

但是我认为我的理解有误,因为我试图在至少两个组件中使用那段代码,但它们都没有淡入或淡出。

这个函数能实现这个效果吗?还是我用了错误的方法来解决问题?


过渡动画库尚未准备就绪,但有解决方法。请参阅官方的Angular Github存储库:https://github.com/angular/angular/issues/9845 - borislemke
这个实用的plunker演示了如何实现你所需要的功能: http://plnkr.co/edit/yJHjL5ap9l4MwOimCyyY?p=preview (home.component.ts) - Ploppy
只是一种hacky的方法是将CSS类附加到所有组件上^^ - Whisher
2个回答

5

Angular 4示例

这是我在主页组件路由上实现淡入动画的方法:

import { Component } from '@angular/core';

import { fadeInAnimation } from '../_animations/index';

@Component({
    moduleId: module.id.toString(),
    templateUrl: 'home.component.html',
    animations: [fadeInAnimation],
    host: { '[@fadeInAnimation]': '' }
})

export class HomeComponent {
}

这是在单独文件中定义的动画。

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

export const fadeInAnimation =
    trigger('fadeInAnimation', [
        // route 'enter' transition
        transition(':enter', [

            // styles at start of transition
            style({ opacity: 0 }),

            // animation and styles at end of transition
            animate('.3s', style({ opacity: 1 }))
        ]),
    ]);

您可以查看此文章获取其他动画和实时演示。


有没有办法在@Component内部使触发器变得有条件?@fadeInAnimation只播放一个动画(即淡入)。我有两种情况:“向左滑动”或“向右滑动”,它们会使相同的组件根据我的条件动画向左(translateX 100%)或向右(translateX -100%)。 - Pageii Studio

3
您的代码看起来是正确的,只需要将动画绑定到一个组件上即可。有两种方法:
一、将其添加到您的模板中,例如添加到 div 标签上:
二、使用 JavaScript 将其添加到组件中:
<div class="container" [@openClose]="'true'">
   ...
</div>

或直接将其应用于您的宿主组件 (<app-component>):

  @Component({
  selector: 'app-component',
  templateUrl: './component.component.html',
  animations: [trigger(
    'openClose',
    [
      transition(":enter", [
        style({ opacity: 0 }),
        animate('2000ms', style({ opacity: 1 }))
      ]),
      transition(":leave", [
        animate('2000ms', style({ opacity: 0 }))
      ])
    ])],
    host: {
        '[@openClose]': 'true',
        'style': 'display: block;'
    },
})

动画是按组件工作的,因此您需要在两个组件上声明动画。

状态更改时可能无法注意到离开动画。官方文档中有一个示例,介绍如何在路由组件中使用动画how to use animations in route components

希望这可以帮助您!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接