57.gif

为路由添加状态标识,此标识即为路由执行动画时的自定义状态

  1. const routes: Routes = [
  2. {
  3. path: "",
  4. component: HomeComponent,
  5. pathMatch: "full",
  6. data: {
  7. animation: "one"
  8. }
  9. },
  10. {
  11. path: "about",
  12. component: AboutComponent,
  13. data: {
  14. animation: "two"
  15. }
  16. },
  17. {
  18. path: "news",
  19. component: NewsComponent,
  20. data: {
  21. animation: "three"
  22. }
  23. }
  24. ]

通过路由插座对象获取路由状态标识,并将标识传递给动画的调用者,让动画执行当前要执行的状态是什么

  1. <div class="routerContainer" [@routerAnimations]="prepareRoute(outlet)">
  2. <router-outlet #outlet="outlet"></router-outlet>
  3. </div>
  1. import { RouterOutlet } from "@angular/router"
  2. export class AppComponent {
  3. prepareRoute(outlet: RouterOutlet) {
  4. return (
  5. outlet &&
  6. outlet.activatedRouteData &&
  7. outlet.activatedRouteData.animation
  8. )
  9. }
  10. }

将 routerContainer 设置为相对定位,将它的直接一级子元素设置成绝对定位

  1. /* styles.css */
  2. .routerContainer {
  3. position: relative;
  4. }
  5. .routerContainer > * {
  6. position: absolute;
  7. left: 0;
  8. top: 0;
  9. width: 100%;
  10. }

创建动画

  1. trigger("routerAnimations", [
  2. transition("one => two, one => three, two => three", [
  3. query(":enter", style({ transform: "translateX(100%)", opacity: 0 })),
  4. group([
  5. query(
  6. ":enter",
  7. animate(
  8. "0.4s ease-in",
  9. style({ transform: "translateX(0)", opacity: 1 })
  10. )
  11. ),
  12. query(
  13. ":leave",
  14. animate(
  15. "0.4s ease-out",
  16. style({
  17. transform: "translateX(-100%)",
  18. opacity: 0
  19. })
  20. )
  21. )
  22. ])
  23. ]),
  24. transition("three => two, three => one, two => one", [
  25. query(
  26. ":enter",
  27. style({ transform: "translateX(-100%)", opacity: 0 })
  28. ),
  29. group([
  30. query(
  31. ":enter",
  32. animate(
  33. "0.4s ease-in",
  34. style({ transform: "translateX(0)", opacity: 1 })
  35. )
  36. ),
  37. query(
  38. ":leave",
  39. animate(
  40. "0.4s ease-out",
  41. style({
  42. transform: "translateX(100%)",
  43. opacity: 0
  44. })
  45. )
  46. )
  47. ])
  48. ])
  49. ])