前言:若是在某些瀏覽器上動畫系統沒法使用,請添加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做用直接綁定在組件