我使用的是Angular 7,并且我正在尝试使用交错来设置组件列表的动画。当列表初始化时,动画可以正常工作,但当列表中的值发生更改时,动画将在列表的旧值上执行,然后新值将不带动画显示。
在我的component.ts中,我有:
export const itemAnimation = [
style({
opacity: 0
}),
stagger(30, [
animate(
'300ms 100ms ease-in',
style({
opacity: 1
})
)
])
];
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.scss'],
animations: [
trigger('animExample', [transition('* => *', [query('.item', itemAnimation, { optional: true })])])
]
})
在模板中:
<div [@animExample]="items">
<div class=".item" *ngFor="let item of items">
<app-example [data]="item"></app-example>
</div>
</div>
似乎动画是在*ngfor
的旧值上完成的,然后渲染新的组件。
发布于 2019-08-16 17:12:23
我不知道这是否会起作用,但这可能是因为ngFor的工作方式。
默认情况下,angular不知道如何跟踪集合中的更改,如果集合中的某些内容发生更改,它将重新呈现所有内容。要解决这个问题,您可以尝试向组件添加跟踪功能。
export const itemAnimation = [
style({
opacity: 0
}),
stagger(30, [
animate(
'300ms 100ms ease-in',
style({
opacity: 1
})
)
])
];
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.scss'],
animations: [
trigger('animExample', [transition('* => *', [query('.item', itemAnimation, { optional: true })])])
]
trackByItem(_: number, item: Item) {
return item.id; // or something from item that would uniquely identify item within collection
}
})
然后将您的模板代码更改为:
<div [@animExample]="items">
<div class=".item" *ngFor="let item of items; trackBy:trackByItem">
<app-example [data]="item"></app-example>
</div>
</div
这只是一种猜测。:)
此外,这是一本非常好的读物,说明了track如何帮助渲染:https://netbasal.com/angular-2-improve-performance-with-trackby-cc147b5104e5
我的假设基于这篇博客文章。
https://stackoverflow.com/questions/57526303
复制相似问题