我如何将Angular2中的动画用于路由器组合



当活动路由器链接更改时,我想动画组件和输出组件。如何编写代码动画代码,以便当路由器更改时,组件逐渐消失,然后另一个逐渐消失?

我一直在尝试的代码是以下内容。

@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 }))
      ])
    ])]
})

,但我认为我的概念错误,因为我试图在至少2个组件中使用该代码,但是它们都没有褪色。

这是可以处理此功能的方法,还是我以错误的方式解决了问题?

示例与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 }))
        ]),
    ]);

有关其他动画和现场演示,您可以查看此帖子

您的代码对我来说似乎是正确的,您只需要将动画绑定到组件即可。有两种方法:

将其添加到模板中,例如Div:

<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;'
    },
})

动画按组件起作用,因此您需要在两个上声明动画。

可能不会在状态变化时注意到休假动画。官方文档有一个有关如何在路由组件中使用动画

中的动画的示例

希望它有帮助!

最新更新