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

Angular路由组件推入推出动画不同步 如何用group()实现并行效果

解决方案

核心问题说明

原实现存在两个核心问题导致动画不同步:

  • 两个独立触发器的触发逻辑由Angular分别调度,天生存在毫秒级的触发时机偏差
  • component2容器提前设置了col-6的50%宽度属性,即使通过transform移出视图,依然会在父容器中占据对应空间,所以component1收缩时右侧会先露出空白,等component2滑入才会填充

模板调整

删除两个子元素的独立触发器,将合并后的触发器绑定到父容器上:

<div class="container" [@slideToggle]="outlet.isActivated ? 'open' : 'close'">
  <div class="component-1">
    <component-1></component-1>
  </div>
  <div class="component-2">
    <router-outlet #outlet="outlet"></router-outlet>
  </div>
</div>

合并后动画代码

将两个元素的动画逻辑合并到同一个触发器中,通过group()包裹保证并行执行:

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

export const slideToggleAnimation = trigger('slideToggle', [
  transition('close => open', [
    group([
      // 组件1同步收缩到50%宽度
      query('.component-1', [
        style({ width: '100%', flex: '0 0 auto' }),
        animate('400ms cubic-bezier(0.35, 0, 0.25, 1)', style({
          width: '50%'
        }))
      ]),
      // 组件2同步从右侧滑入
      query('.component-2', [
        style({ width: '50%', flex: '0 0 auto', transform: 'translateX(100%)' }),
        animate('400ms cubic-bezier(0.35, 0, 0.25, 1)', style({
          transform: 'translateX(0%)'
        }))
      ])
    ])
  ]),
  transition('open => close', [
    group([
      // 组件1同步拉伸到100%宽度
      query('.component-1', [
        animate('400ms cubic-bezier(0.35, 0, 0.25, 1)', style({
          width: '100%'
        }))
      ]),
      // 组件2同步向右侧滑出
      query('.component-2', [
        animate('400ms cubic-bezier(0.35, 0, 0.25, 1)', style({
          transform: 'translateX(100%)'
        }))
      ])
    ])
  ])
]);

配套样式调整

给父容器添加弹性布局和溢出隐藏属性,避免动画过程中出现布局错乱:

.container {
  display: flex;
  width: 100%;
  overflow: hidden;
}
.component-1, .component-2 {
  flex-shrink: 0;
}

组件注册配置

在使用动画的组件@Component装饰器中注册动画即可:

@Component({
  // 其他配置省略
  animations: [slideToggleAnimation]
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:12:00