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

Angular 4动画中使用变量:动态设置组件展开区起始高度

动态设置Angular动画的起始高度

没问题,这个需求在Angular动画里很容易实现,咱们可以通过绑定动态属性值来让起始高度根据列表元素数量自动切换,给你两种亲测可行的方案:

方案一:通过组件计算属性绑定动态高度

首先在组件类里定义一个计算属性,根据list_length的值返回对应的起始高度:

@Component({
  selector: 'awaken-card',
  templateUrl: 'awaken-card.html',
  animations: [
    trigger('heroState', [
      // 使用占位符绑定动态高度,同时设置默认值
      state('inactive', style({ height: '{{initialHeight}}' })),
      // 通配符状态保留,用于展开后的自适应高度
      state('*', style({ height: '*' })),
      // 定义过渡动画
      transition('inactive <=> *', animate('300ms ease-in-out'))
    ], { 
      // 设置参数默认值,避免未绑定时报错
      params: { initialHeight: '120px' } 
    })
  ]
})
export class AwakenCardComponent {
  @Input() list_length: number;
  // 计算属性,根据列表数量返回对应高度
  get initialHeight(): string {
    return this.list_length > 1 ? '50px' : '120px';
  }
  // 控制展开/收起的状态,比如默认是inactive
  currentState = 'inactive';
}

然后在模板里使用动画时,把动态高度参数传进去:

<div [@heroState]="{ value: currentState, params: { initialHeight: initialHeight } }">
  <!-- 你的可展开内容 -->
</div>

方案二:直接在动画样式中使用表达式

如果不想额外定义计算属性,也可以直接在动画的style里写三元表达式,前提是list_length是组件的公共属性:

@Component({
  selector: 'awaken-card',
  templateUrl: 'awaken-card.html',
  animations: [
    trigger('heroState', [
      state('inactive', style({ 
        height: '{{list_length > 1 ? "50px" : "120px"}}' 
      })),
      state('*', style({ height: '*' })),
      transition('inactive <=> *', animate('300ms ease-in-out'))
    ], {
      params: { list_length: 0 } // 设置默认值
    })
  ]
})
export class AwakenCardComponent {
  @Input() list_length: number;
  currentState = 'inactive';
}

模板里同样需要传递参数:

<div [@heroState]="{ value: currentState, params: { list_length: list_length } }">
  <!-- 你的可展开内容 -->
</div>

注意事项

  • 确保list_length的值在组件初始化或更新时能正确传递/计算,这样动画参数才会实时更新
  • 过渡动画的时长和缓动函数可以根据你的需求调整,比如把300ms ease-in-out改成你需要的配置
  • 通配符状态*会让元素高度自适应内容,刚好满足展开后的需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:06:40