如何在Angular中为* ngFor设置动画?
问题描述:
我需要为ngFor
列表添加动画并显示它.每个元素都应该有一个过渡,比如说类似的东西.
I need to animate an ngFor
list as it is populated and shown. Each element should have a transition, let's say something like this.
我该怎么做?
答
它有一些问题,因为ngFor
进行了一些多余的添加/删除操作,使项目无法显示动画,
It has a few issues because ngFor
does a few redundant add/removes which cause items to be animated which shouldn't:
import {Component} from 'angular2/core';
import { Component, Directive, OnDestroy, Input } from 'angular2/core';
@Component({
selector: 'my-app',
template: `<div (click)="$event.preventDefault()">
<button type="button" (click)="pushItem()">Push</button>
<button type="button" (click)="removeItemLast()">Remove Last</button><br/>
<button type="button" (click)="unshiftItem()">Unshift</button>
<button type="button" (click)="removeItemFirst()">Remove First</button><br/>
<ul>
<li class="my-animation" *ngFor="#item of items">
{{item.title}}
</li>
</ul>
</div>`
})
export class AppComponent {
private count:number = 1;
public items: Array<any>;
constructor() {
console.clear();
this.items = [];
this.items.push(this.newItem());
this.items.push(this.newItem());
}
pushItem() {
this.items.push(this.newItem());
},
removeItemLast() {
if(this.items.length > 0) this.items.splice(this.items.length - 1, 1);
},
unshiftItem() {
this.items.unshift(this.newItem());
},
removeItemFirst() {
if(this.items.length > 0) this.items.splice(0, 1);
},
newItem() {
return {title: 'Item' + this.count++};
}
}
@keyframes MyAnimation {
0% {
padding-left: 100px;
}
100% {
padding-left: 0px;
}
}
.my-animation {
animation: MyAnimation 1s;
}
柱塞示例(RC.x) https://github.com/angular/angular/issues/7239 演示了此问题
更新
这是很久以前解决的
正在工作 关于stackblitz的演示
working Demo on stackblitz