You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular路由中集成fadeIn fadeOut淡入淡出过渡效果

现有代码核心问题

  • CSS语法错误,::ng-deep伪类书写顺序错误,且缺少宿主元素的相对定位配置,导致路由组件的绝对定位基准不符合预期
  • 动画配置使用group实现并行执行,和Angular官网先淡出旧页面、再淡入新页面的时序不一致,且缺少离开元素的初始透明度声明

正确实现步骤

1. 修正组件CSS样式

在放置router-outlet的组件样式中添加如下代码:

/* 宿主元素设为相对定位,作为子路由组件的定位基准 */
:host {
  position: relative;
  display: block;
  width: 100%;
  min-height: 100vh;
  overflow: hidden;
}

/* 修正::ng-deep写法,匹配路由出口后的激活组件 */
::ng-deep router-outlet ~ * {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}

2. 修正路由动画配置

修改route-transition-animations.ts中的动画定义,使用sequence实现顺序执行的淡入淡出效果,和Angular官网表现一致:

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

export const fadeAnimation = trigger('routeAnimations', [
  transition('* => *', [
    // 预先设置即将进入的页面透明度为0
    query(':enter', [
      style({ opacity: 0 })
    ], { optional: true }),

    // 顺序执行动画:先淡出旧页面,再淡入新页面
    sequence([
      query(':leave', [
        style({ opacity: 1 }),
        animate('200ms ease-out', style({ opacity: 0 }))
      ], { optional: true }),
      query(':enter', [
        animate('200ms ease-in', style({ opacity: 1 }))
      ], { optional: true })
    ])
  ])
]);

如果需要轻微的交叉过渡效果,可以把sequence替换为group,给进入动画加100ms延迟即可:

group([
  query(':leave', [
    style({ opacity: 1 }),
    animate('300ms ease-out', style({ opacity: 0 }))
  ], { optional: true }),
  query(':enter', [
    style({ opacity: 0 }),
    animate('300ms 100ms ease-in', style({ opacity: 1 }))
  ], { optional: true })
])

3. 确认基础配置正常

  • 确保根模块中已导入BrowserAnimationsModule
  • 放置router-outlet的组件元数据中已声明animations: [fadeAnimation]
  • 组件模板中正确绑定动画触发器:
<div [@routeAnimations]="outlet.isActivated">
  <router-outlet #outlet="outlet"></router-outlet>
</div>

内容的提问来源于stack exchange,提问作者robb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 19:36:00