前言:若是在某些浏览器上动画系统没法使用,请添加web-animation-js,javascript
"npm install web-animation-js”.html
正文:java
咱们知道在angular2提供了动画的功能,可以在状态变化的时候进行样式切换,切换的时候使用相应的transition或者animate,如web
flyIn.tsnpm
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.htmlangular2
<div [@flyIn]="true"> </div>
component.tsless
@Component({ selector: 'index', templateUrl: './index.component.html', styleUrls: ['./index.component.less'], animations: [flyIn] })
正如上述代码,void=>*(:enter)状态时有效,可是*=>void(:leave)状态时无效。动画
缘由其实很简单,就是state的样式,应用在了component.html上。code
外层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做用直接绑定在组件