首页 > 解决方案 > 角度 - 仅在页面刷新时触发的路由动画

问题描述

我有一种情况,我为路线设置的动画仅在刷新浏览器页面时触发。当我导航到应用程序中的不同路线时,不会应用动画。

这是我的router-animations.ts

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

export function slideLeft() {
    return slide();
}

function slide() {
    return trigger('slide', [
        state('void', style({ position: 'absolute', width: '100%' })),
        state('*', style({ position: 'absolute', width: '100%' })),
        transition('void => *', [
            style({ transform: 'translateX(100%)', opacity: 0 }),
            animate(
                '1s ease-in-out',
                style({ transform: 'translateX(0%)', opacity: 1 })
            ),
        ]),
        transition('* => void', [
            style({ transform: 'translateX(0%)', opacity: 1 }),
            animate(
                '1s ease-in-out',
                style({ transform: 'translateX(-100%)', opacity: 0 })
            ),
        ]),
    ]);
}

我的app.component.html

<div [@slide]="prepareRoute(outlet)" >
    <router-outlet #outlet="outlet"></router-outlet>
</div>

app.component.ts:_

import { slideLeft } from './router-animations'

@Component({
  selector: 'app-root',
  animations: [slideLeft()],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})

export class AppComponent {
  title = 'ShopCompanionApp';

  prepareRoute(outlet: RouterOutlet) {
      return outlet && outlet.activatedRouteData && outlet.activatedRouteData['animation'];
  }
}

最后,这是我的路线:

const appRoutes: Routes = [
    { path: "", component: LoginShopComponent },
    { path: "login/store", component: LoginShopComponent },
    { path: "login/account", component: LoginAccountComponent },
    { path: "mystore/manage", component: SlotsManagementComponent, canActivate: [AuthGuard] },
    { path: "mystore/orders", component: OrdersComponent, canActivate: [AuthGuard] },
    { path: "mystore/orders/:id", component: OrderDetailsComponent, canActivate: [AuthGuard] },
    { path: "**", redirectTo: "mystore/manage", pathMatch: "full" }
]

我在这里想念什么?

提前致谢。

标签: htmlangulartypescriptangular-routingangular-animations

解决方案


我不是 100% 确定规格,但您可以尝试监听路线变化,如果 url 符合您的条件,则应用动画。

我删除了prepareRoute,并将其替换为shouldSlide变量。

<div [@slide]="shouldSlide" >
    <router-outlet #outlet="outlet"></router-outlet>
</div>
import { Router, NavigationEnd } from '@angular/router';
export class AppComponent {
  title = 'ShopCompanionApp';
  shouldSlide = false;

  constructor(private router: Router) {
    router.events.subscribe((evt) => { // will trigger each time there's a route change.
      if(evt instanceof NavigationEnd){
        this.shouldSlide = evt.url.match('animation');
      }
    });
  }
  
  // TODO unsubscribe when the component is destroyed
}

推荐阅读