我对Angular 2中的动画不熟悉,可能会忽略一些明显的问题,但是如何动画化由*ngFor循环生成的元素呢?似乎动画与组件相关,必须在@Component装饰器中定义?
唯一的解决方案是创建一个内部组件,并在*ngFor中创建它,然后对其进行动画处理吗?
这是一个使用淡入动画的示例,适用于在*ngFor
循环中生成的元素。
my.component.ts
@Component({
selector: ...,
templateUrl: 'my-component.html',
styleUrls: ...,
animations: [
trigger('fadeIn', [
transition(':enter', [
style({ opacity: '0' }),
animate('.5s ease-out', style({ opacity: '1' })),
]),
]),
],
})
我的组件.html
<div *ngFor="let item of myArray" @fadeIn>I'm an Item</div>
注意: 如果您想使用具有特定状态的动画,则应绑定该状态,例如:
[@myAnimation]="'myState'"
@Component({
selector: ...,
templateUrl: 'my-component.html',
styleUrls: ...,
animations: [
trigger('inOutAnimation', [
state('in', style({ opacity: 1 })),
transition(':enter', [style({ opacity: '0' }), animate('.5s ease-out', style({ opacity: '1' }))]),
transition(':leave', [style({ opacity: '1' }), animate('.5s ease-out', style({ opacity: '0' }))]),
]),
],
})
<div *ngFor="let item of myArray" [@inOutAnimation]="'in'">
state('in',style ...)
放在那里有什么用?即使没有它也可以工作。 - Sahil Babbar
[]
也不是必须的。已相应地更新了答案。 - Ploppy