首页 > 解决方案 > 对使用 ngFor 显示的数组进行排序会应用 void 动画状态

问题描述

<ul>
<li *ngFor="let user of users; trackBy: identify; index as i" [@anim]="user.id" (@anim.done)="test($event)">
    {{user.name}} (@{{user.id}})
</li>
</ul>

  constructor() {
    this.change1();
  }

  change1(): void {
    this.users = [user1, user2, user3, user4, user5];
  }
  change2(): void {
    this.users = [user2, user1, user3, user4, user5];
  }

  identify(index: number, item: User) {
    return item.id;
  }

  test(e) {
    console.log(e);
  }


const user1 = { id: 1, name: 'one' };
const user2 = { id: 2, name: 'two' };
const user3 = { id: 3, name: 'three' };
const user4 = { id: 4, name: 'four' };
const user5 = { id: 5, name: 'five' };

https://stackblitz.com/edit/angular-ivy-h7ohwc?file=src/app/app.component.html

这个例子说明了这个问题。我们有一个使用 trackBy + 每个元素都有动画的数组。在控制台中对数组(按钮 change2)进行排序后,您可以看到元素 2 将状态从 2 更改为 void。如果它不改变,是否有可能获得状态 2?为什么会变废为宝?

标签: angularsortinganimationngforangular-animations

解决方案


推荐阅读