Angular 13中如何延迟指定时间后移除状态样式
解决方案:通过状态变量+定时器实现自动重置动画样式
问题核心在于你当前的getState()仅在Redis变更时执行一次,没有后续触发状态重置的逻辑。可以通过组件内维护动画状态变量,配合定时器实现3秒后自动清除样式的效果,具体实现如下:
1. 调整组件动画与状态管理
import { Component } from '@angular/core'; import { trigger, state, style, animate, transition } from '@angular/animations'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', animations: [ trigger('change', [ state('increase', style({ backgroundColor: 'rgb(3, 190, 3)' })), state('decrease', style({ backgroundColor: 'red' })), state('*', style({ backgroundColor: 'transparent' })), // 通用默认状态 // 优化过渡动画,让样式变化更平滑 transition('* => increase, * => decrease', animate('300ms ease-in')), transition('increase => *, decrease => *', animate('300ms ease-out')) ]) ] }) export class YourComponentComponent { animationState: string = ''; tennisWorkerObject: any; private animationTimer?: NodeJS.Timeout; // 用于存储定时器ID,避免重复触发 // 假设这是你的Redis变更监听逻辑 handleRedisUpdate(newData: any) { const oldValue = this.tennisWorkerObject?.konecenTip?.home || 0; const newValue = newData.konecenTip.home; // 清除之前的定时器,避免频繁更新时状态被错误重置 if (this.animationTimer) { clearTimeout(this.animationTimer); } // 设置对应动画状态 if (newValue > oldValue) { this.animationState = 'increase'; } else if (newValue < oldValue) { this.animationState = 'decrease'; } // 3秒后重置状态 this.animationTimer = setTimeout(() => { this.animationState = ''; this.animationTimer = undefined; }, 3000); // 更新数据对象 this.tennisWorkerObject = newData; } }
2. 修改模板绑定
将原来的getState()调用替换为组件内的animationState变量,确保状态变化能触发动画更新:
<div [@change]="animationState" class="col-4 p-0"> {{tennisWorkerObject.konecenTip.home | number:"1.2-2"}} </div>
关键说明
- 状态变量替代方法调用:Angular会监听组件变量的变化触发动画,比单次调用
getState()更可靠,能确保状态重置时动画正常执行。 - 定时器防重复:维护
animationTimer变量,每次Redis更新时清除旧定时器,避免多次推送时旧定时器覆盖新状态。 - 优化动画过渡:将原有的10ms动画时长调整为300ms,让背景色变化更自然,同时区分进入和退出动画的缓动效果。
内容的提问来源于stack exchange,提问作者Vladimir99
相关产品推荐
相关产品推荐

