1. 程式人生 > >《Angular2入門系列實踐》——實現頁面動畫效果

《Angular2入門系列實踐》——實現頁面動畫效果


前言
    在前端的路上越走越遠,也希望利用angular2使自己的頁面效果更加美觀,所以從官網上學習了一下

內容

    1.寫animation.ts
import { animate, AnimationEntryMetadata, state, style, transition, trigger } from '@angular/core';


export const slideInDownAnimation: AnimationEntryMetadata =
  trigger('routeAnimation', [
    state('*',
      style({
        opacity: 1
, transform: 'translateX(0)' }) ), transition(':enter', [ style({ opacity: 0, transform: 'translateX(-100%)' }), animate('0.2s ease-in') ]), transition(':leave', [ animate('0.5s ease-out', style({ opacity: 0, transform: 'translateY(100%)'
})) ]) ]);

    2.在使用效果的元件ts中引入,我定義了一個demo.ts

import 'rxjs/add/operator/switchMap';
import { Component, OnInit, HostBinding } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';

import { slideInDownAnimation } from '../animations';  //引入滑動頁面的效果

import { Hero, HeroService }  from './hero.service'
; @Component({ template: ` <h2>HEROES</h2> <div *ngIf="hero"> <h3>"{{ hero.name }}"</h3> <div> <label>Id: </label>{{ hero.id }}</div> <div> <label>Name: </label> <input [(ngModel)]="hero.name" placeholder="name"/> </div> <p> <button (click)="gotoHeroes()">Back</button> </p> </div> `, animations: [ slideInDownAnimation ] }) export class HeroDetailComponent implements OnInit { @HostBinding('@routeAnimation') routeAnimation = true; @HostBinding('style.display') display = 'block'; @HostBinding('style.position') position = 'absolute'; hero: Hero; constructor( private route: ActivatedRoute, private router: Router, private service: HeroService ) {} ngOnInit() { this.route.paramMap .switchMap((params: ParamMap) => this.service.getHero(params.get('id'))) .subscribe((hero: Hero) => this.hero = hero); } gotoHeroes() { let heroId = this.hero ? this.hero.id : null; this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]); } }

總結
    主要就是在需要引入滑動的元件中引入這個效果,就達到了預期的成效!希望對你有幫助!