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

Angular 14类绑定未触发scaleY过渡动画问题

问题描述

在Angular 14中通过类绑定切换filled类时,transform: scaleY()的过渡动画完全失效,元素状态瞬间切换;但使用:hover选择器测试时,过渡动画正常工作。已确认Angular能正确添加/移除filled类,且排查过常见CSS语法错误,问题仍未解决。

相关代码如下:

component.html

<div class="bar" [class.end]="typeEnd">
  <span *ngFor="let portion of filledPortion; let i = index" class="portion" [class.filled]="portion"></span> 
</div>

component.scss

.bar {
  .portion {
    position: relative;
    width: 2rem;
    height: 1.5rem;
    clip-path: polygon(100% 0, 0 0, 50% 100%);
    &::before {
      content: '';
      display: block;
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      transform-origin: bottom;
      transform: scaleY(0);
      background-color: var(--red);
      transition: transform .250s cubic-bezier(0.4, 0.0, 0.2, 1);
      z-index: 1;
    }
    &.filled::before {
      transform: scaleY(1);
    }
  }
}

.end {
  .portion {
    &::before , &::after {
      background-color: #fff;
    }
  }
}
解决方案

问题核心是*ngFor没有设置trackBy函数,当filledPortion数组变化时,Angular会销毁并重新渲染所有<span>元素,而非修改现有元素的filled类。新渲染的元素直接应用最终状态的样式,自然不会触发CSS过渡动画。

修复步骤:

  1. 在组件类中添加trackBy函数,让Angular复用已有DOM元素
  2. 修改*ngFor指令,使用该trackBy函数

修改后的代码

component.ts

// 添加trackBy函数
trackByIndex(index: number): number {
  return index;
}

component.html

<div class="bar" [class.end]="typeEnd">
  <span *ngFor="let portion of filledPortion; let i = index; trackBy: trackByIndex" class="portion" [class.filled]="portion"></span> 
</div>

原理说明

添加trackBy后,Angular会根据返回的索引值识别元素,数组变化时只会更新对应元素的filled类,而非重建元素。此时CSS能捕捉到伪元素transform属性的状态变化,正常触发过渡动画。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 11:16:01