前言:如果在某些浏览器上动画系统无法使用,请添加web-animation-js,
"npm install web-animation-js”.
正文:
我们知道在angular2提供了动画的功能,能够在状态变化的时候进行样式切换,切换的时候使用相应的transition或者animate,如
flyIn.ts
import {trigger,state,style,transition,animate} from '@angular/core'; export const flyIn = trigger('flyIn', [ state('*', style({transform:'translateX(0)'})), transition('void => *', [ animate(100, style({transform: 'translateX(-15px)'})) ]), transition('* => void', [ animate(100, style({transform: 'translateX(15px)'})) ]) ]);
当我们在NG2项目中的时候使用这种,却没有离场动画,也就是当 *=>void(:leave)状态时,无效
component.html
<div [@flyIn]="true"> </div>
component.ts
@Component({ selector: 'index', templateUrl: './index.component.html', styleUrls: ['./index.component.less'], animations: [flyIn] })
正如上述代码,void=>*(:enter)状态时有效,但是*=>void(:leave)状态时无效。
原因其实很简单,就是state的样式,应用在了component.html上。
外层index在router-outlet中,当进行路由的时候,component直接被移除掉了,相当于display:none,这时动画肯定就是不起作用的。
所以我们需要把动画这样子添加,
import {Component,HostBinding} from "@angular/core";
@Component({
selector: 'index',
templateUrl: './index.component.html',
styleUrls: ['./index.component.less'],
animations: [flyIn]
})
export class IndexComponent{
@HostBinding("@flyIn") flyIn=true;
@HostBinding('style.display') display = 'block';
@HostBinding('style.position') position = 'absolute';
}
这时,我们再去看动画就生效了。hostbinding作用直接绑定在组件