Angular 4动画:淡入淡出视图

4

我希望在路由变化时视图能够淡入淡出。我似乎已经正确设置了组件,但需要正确使用动画语法。

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

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个回答

8
这对于我的路由动画很有效:
Typescript:
  ....
   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


我已经尝试过了,但是没有发生过渡,并且我没有收到任何控制台错误。你可以向我展示你的组件吗? - AngularM

3
我发现您需要将显示设置为块以使动画工作,如下所示:
@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() {
  }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接