在Angular2中,如何为辅助路径中加载的组件设置动画?

时间:2016-11-15 16:37:26

标签: angular

我有一个侧栏组件,它被加载到命名/辅助路由中。这很好用。

此外,我在此组件元数据中设置了一些动画,用于创建有效的幻灯片。当我“正常”加载此组件时,例如单击按钮时,此动画也可以正常工作。

但是,当我在辅助路线中添加此组件时,动画不会触发。该组件即刻呈现。

为什么呢?我怎样才能解决这个问题?请参阅下面的代码。

sidebar.component.ts

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

    @Component({
      selector: 'sidebar',
      templateUrl: 'sidebar.component.html',
      styleUrls: ['sidebar.component.scss'],
      animations: [trigger('slideIn', [
        state('false', style({
          width: '0'
        })),
        state('true', style({
          width: '18.75rem'
        })),
        transition('0 => 1', animate('300ms ease-in')),
        transition('1 => 0', animate('300ms ease-out'))
      ])]
    })
    export class SidebarComponent {
      shouldAnimate: boolean;

      constructor(private route: ActivatedRoute){
         if (this.route.outlet === 'sidebar') {
           this.shouldAnimate = true; // Yes, I do enter here every time
         }
      }
    }

sidebar.component.html

<div id="sidebar"
  [@slideIn]="shouldAnimate">
</div>
来自app.routes.ts的

{ path: 'profile', outlet: 'sidebar', component: SidebarComponent }
来自app.component.ts的

<router-outlet name="sidebar"></router-outlet>

1 个答案:

答案 0 :(得分:2)

我自己想通了。事实证明,当您重新加载组件时,它所拥有的第一个状态是void,并且需要在组件的元数据的animations:部分中正确配置。

所以我添加了一个新的状态void,并添加了从void到1的转换。

基本上我改变了这个:

trigger('isVisibleChanged', [
  state('false', style({
    width: '0'
  })),
  state('true', style({
    width: '18.75rem'
  })),
  transition('0 => 1', animate('300ms ease-in')),
  transition('1 => 0', animate('300ms ease-out'))
]);

到此:

trigger('isVisibleChanged', [
  state('void', style({
    width: '0'
  })),
  state('false', style({
    width: '0'
  })),
  state('true', style({
    width: '18.75rem'
  })),
  transition('0 => 1', animate('300ms ease-in')),
  transition('1 => 0', animate('300ms ease-out')),
  transition('void => 1', animate('300ms ease-in'))
]);
相关问题