用于淡入和淡出视图的Angular 4动画

时间:2017-09-25 15:10:14

标签: angular angular-animations

我只是希望视图在路线变化时淡入淡出。我已经正确设置了组件,但我认为需要让动画语法正确。

这是我当前的动画尝试。 我将此动画导入我的组件:

import {trigger, state, animate, style, transition} from '@angular/animations';

export function routerTransition() {
  return fadeInAndOut();
}

function fadeInAndOut() {
  return trigger('routerTransition', [
    transition(':enter', [
      style({opacity: 0}),
      animate(3000, style({opacity: 1}))
    ]),
    transition(':leave', [
      animate(3000, style({opacity: 0}))
    ])
  ]);
}

这是我导入转换的组件之一:

import { Component } from "@angular/core";
import { routerTransition } from "../../animations/fade.animation";

@Component({
  selector: "about-users",
  templateUrl: "./about.component.html",
  animations: [routerTransition()],
  host: { '[@routerTransition]': '' } 
})

export class AboutComponent {  
  constructor() {
  }
}

2 个答案:

答案 0 :(得分:3)

这适用于路由动画:

<强>打字稿:

  ....
   animations: [
    trigger('routerTransition', [
      transition('* <=> *', [    
        query(':enter, :leave', style({ position: 'fixed', opacity: 1 })),
        group([ 
          query(':enter', [
            style({ opacity:0 }),
            animate('1000ms ease-in-out', style({ opacity:1 }))
          ]),
          query(':leave', [
            style({ opacity:1 }),
            animate('1000ms ease-in-out', style({ opacity:0 }))]),
        ])
      ])
    ])
   ]

<强> HTML:

<nav>
  <a routerLink="/page1" routerLinkActive="active">Page1</a>
  <a routerLink="/page2" routerLinkActive="active">Page2</a>
</nav>
<br><br>
<main [@routerTransition]="page.activatedRouteData.state">
  <router-outlet #page="outlet"></router-outlet>
</main>

DEMO

答案 1 :(得分:2)

我发现您需要将显示设置为阻止动画生效,如下所示:

@HostBinding('style.display') display = 'block';

此外,使用最新的Angular,您需要使用HostBinding代替host

请参阅我的完整档案:

import { Component, OnInit, HostBinding } from '@angular/core';
import { slideInDownAnimation, fadeInAnimation } from './../checkout-animations';

@Component({
  selector: 'app-checkout-two',
  templateUrl: './checkout-two.component.html',
  styleUrls: ['./checkout-two.component.scss', './../checkout.component.scss'],
  animations: [slideInDownAnimation]
})

export class CheckoutTwoComponent implements OnInit {
  @HostBinding('@routeAnimation') routeAnimation = true;
  @HostBinding('style.display') display = 'block';

  constructor() { }

  ngOnInit() {
  }

}