在表达式值更改时添加动画 - 角度 5



我在一个名为"pointsBalance"的页面上有一个名为"pointsBalance"的表达式,它显示数值。它连接到一个可观察对象,当 pointsBalance 值上升时,我想将颜色更改为绿色,然后恢复为原始颜色,如果值下降,则更改为红色。我以为我可以使用Angular 5新的动画别名:增量和:d ecrement,但我一直遇到问题。

用于显示积分余额的 HTML:

<div [@valueAnimation]="pointsBalance">{{ pointsBalance }}</div> 

设置动画和点的代码可观察的平衡:

import { Component, OnInit, Input } from '@angular/core';
import { trigger, style, transition, animate, keyframes, query, 
stagger, state, group } from '@angular/animations';
import { CompetitionsService } from "../../../shared/index";
@Component({
selector: 'points',
templateUrl: './...html',
animations: [
trigger('valueAnimation', [
transition(':increment', group([
query(':enter', [
style({ color: 'green', fontSize: '50px' }),
animate('0.8s ease-out', style('*'))
])
])),
transition(':decrement', group([
query(':enter', [
style({ color: 'red', fontSize: '50px' }),
animate('0.8s ease-out', style('*'))
])
]))
])
]
})
export class CompetitionDetailsComponent implements OnInit {
pointsBalance: number;
constructor(private competitionsService: CompetitionsService, ) { }
ngOnInit() {
this.competitionsService.updatePointsBalance$.subscribe(
(pointsBalance) => {
this.pointsBalance = pointsBalance;
}
)
}
}

当积分余额值更改时,我收到此控制台错误:

错误

错误:由于以下触发器转换失败,无法处理动画 @valueAnimation由于以下原因而失败:

  • query(":enter")返回零个元素。(如果您希望允许此操作,请使用query(":enter", { optional: true })

有谁知道为什么我会收到此错误?还是有其他方法可以实现这一点?谢谢。

:enter动画将仅对新创建的元素进行动画处理。您的"黑客"解决方法有效,因为它会在值更改时强制重新创建内部跨度。我认为您想要的是删除:enter查询。您希望在数字进入/减少时进行动画处理,并且动画与要添加的元素无关。

我从这里和这里找到了修复程序。

<div [@valueAnimation]="pointsBalance"><span *ngFor="let pointsBalance of [ pointsBalance ]">{{ pointsBalance }}</span></div>

虽然感觉有点笨拙。

我只是要粘贴代码,就像本杰明·金德尔所说,我试过了,它奏效了:

animations: [
trigger('valueAnimation', [
transition(':increment', [
style({ color: 'green', fontSize: '50px' }),
animate('0.8s ease-out', style('*'))
]
),
transition(':decrement', [
style({ color: 'red', fontSize: '50px' }),
animate('0.8s ease-out', style('*'))
]
)
])
]

最新更新