angular - 元素上的角度动画
问题描述
我有一个显示项目列表的表格。通过对服务器执行 http get 请求并使用轮询来更新此项目列表,并且仅在响应发生更改时才呈现响应。
我想要的是在表格的行上附加一个动画,如果这一行是新的,则执行动画。现在每次响应是新的并且组件被重新渲染时都会触发动画,但是它会为表的所有行而不是新行触发。
我有main.component.ts
其中包含表和另一个组件,这些是传递给他们的孩子的可观察的。我将 event$ 流与要显示的事件数组一起传递,以及 newSeenPlatformIds$ 为仅在发生更改时获取的事件数组发出 id 的最大值。我用它来触发动画,如果这个数字发生变化,就会出现一个新行。
ngOnInit() {
// events that get rendered in the table
this.events$ = timer(0, 5000).pipe(
switchMap(() => this.eventsService.fetchLastEvents()),
distinctUntilChanged(
(curr, prev) =>
Math.max(...curr.map(currItem => currItem.id)) === Math.max(...prev.map(prevItem => prevItem.id))
)
);
// everytime a new id is emitted, I want the row containing the event with event.id to animate
this.newSeenPlatformIds$ = this.events$.pipe(
map(events => Math.max(...events.map(event => event.id))),
distinctUntilChanged()
);
}
现在定义动画的表格组件:
import { Component, OnInit, Input } from '@angular/core';
import { Observable } from 'rxjs/internal/Observable';
import { Event } from 'src/app/shared/interfaces/event';
import { trigger, style, transition, animate } from '@angular/animations';
import { tap } from 'rxjs/operators';
@Component({
selector: 'app-last-events-grid',
templateUrl: './last-events-grid.component.html',
styleUrls: ['./last-events-grid.component.scss'],
animations: [
trigger('newRowAnimation', [
transition('* <=> *', [style({ opacity: 0 }), animate('1000ms', style({ opacity: 1 }))])
])
]
})
export class LastEventsGridComponent implements OnInit {
@Input() events$: Observable<Event[]>;
@Input() newSeenPlatformIds$: Observable<number>;
newSeenPlatformId: number;
triggerAnimation = false;
constructor() {}
ngOnInit() {
this.newSeenPlatformIds$.pipe(tap(id => console.log(id))).subscribe(id => {
this.newSeenPlatformId = id;
this.triggerAnimation = true;
});
}
}
最后是模板:
<div class="flex justify-center">
<table class="w-full mx-10">
<thead class="text-gray-500">
<tr>
<th class="cell-main"></th>
<th class="cell-main">DESCRIPTION</th>
<th class="cell-main">TIME</th>
<th class="cell-main">READER</th>
<th class="cell-main">STATE</th>
<th class="cell-main">NEXT CHECK</th>
<th class="cell-main">READINGS LEFT</th>
</tr>
</thead>
<tbody>
<tr
[@newRowAnimation]="triggerAnimation && event.id === newSeenPlatformId"
[ngClass]="{ 'row-nok': event.estado === false }"
class="rounded overflow-hidden shadow-lg text-xl text-gray-500"
app-event-item
*ngFor="let event of events$ | async"
[event]="event"
></tr>
</tbody>
</table>
</div>
解决方案
如果有人遇到同样的问题,我可以通过查看@tsiro 建议的“trackBy”来找到另一个问题,我只是跟着它工作:
推荐阅读
- android - 单击工具栏中的搜索按钮后视图未正确显示
- google-cloud-functions - 带有 pub sub 触发器的云功能不适用于跨区域
- javascript - 如何在 Javascript 中获取上一个日期?
- php - 如何根据不同的变量保存变量?
- jquery - $ 不是函数 - 嵌套函数
- c# - 有没有办法“加载”浏览器但不显示任何内容?头孢夏普
- html - 如何消除对表单字段的关注
- android - FirebasePerformance:方法跟踪(使用 @AddTrace)不显示在 Logcat 中
- sql - 根据另一行填充行(将价格从分支 0 复制到所有其他分支)
- python - 将对象方法作为函数参数传递给python中的方法链接