Angular 5 并且仅在 'new' 项中过渡
Angular 5 and transition only in 'new' items
我的组件模板呈现列表:
<div class="row">
<div *ngFor="let m of activeModules" [@enterAnimation]>
{{ m.name }}
</div>
</div>
组件对其进行动画处理
@Component({
selector: 'app-client-detail',
templateUrl: './client-detail.component.html',
styleUrls: ['./client-detail.component.scss'],
animations: [
trigger(
'enterAnimation', [
transition(':enter', [
style({ opacity: 0 }),
animate('1000ms', style({ opacity: 1}))
]),
transition(':leave', [
style({ opacity: 1 }),
animate('1000ms', style({ opacity: 0}))
])
]
)
]
})
export class ClientDetailComponent implements OnInit {
activeModules = [{ name: 'modulo 1'}, { name: 'modulo 2'}];
}
效果很好,'divs' 从不透明度过渡。
如果我这样做:
ngOnInit() {
Observable.timer(2000).subscribe(() => {
this.activeModules = [{ name: 'modulo 1'}, { name: 'modulo 3'}, { name: 'modulo 2'}];
}
activeModules 的数组已更新,模板再次呈现带有转换的列表。我的问题是我只需要数组中的 'new' 项(在本例中为中间的项)进行过渡。可能吗?
当然,你只需要推送你的项目而不是再次创建你的数组。
让我们为此创建一个函数:
pushAt(arr, index, item) {
arr.splice(index, 0, item);
}
现在你可以
ngOnInit() {
Observable.timer(2000).subscribe(() => this.pushAt(this.activeModules, 1, { name: 'Modulo 2' }));
}
编辑 也许您可以尝试使用自定义跟踪功能:
customTrackBy(index, item) { return index; }
在你的HTML
<div *ngFor="let m of activeModules; trackBy: customTrackBy;" [@enterAnimation]>
我的组件模板呈现列表:
<div class="row">
<div *ngFor="let m of activeModules" [@enterAnimation]>
{{ m.name }}
</div>
</div>
组件对其进行动画处理
@Component({
selector: 'app-client-detail',
templateUrl: './client-detail.component.html',
styleUrls: ['./client-detail.component.scss'],
animations: [
trigger(
'enterAnimation', [
transition(':enter', [
style({ opacity: 0 }),
animate('1000ms', style({ opacity: 1}))
]),
transition(':leave', [
style({ opacity: 1 }),
animate('1000ms', style({ opacity: 0}))
])
]
)
]
})
export class ClientDetailComponent implements OnInit {
activeModules = [{ name: 'modulo 1'}, { name: 'modulo 2'}];
}
效果很好,'divs' 从不透明度过渡。 如果我这样做:
ngOnInit() {
Observable.timer(2000).subscribe(() => {
this.activeModules = [{ name: 'modulo 1'}, { name: 'modulo 3'}, { name: 'modulo 2'}];
}
activeModules 的数组已更新,模板再次呈现带有转换的列表。我的问题是我只需要数组中的 'new' 项(在本例中为中间的项)进行过渡。可能吗?
当然,你只需要推送你的项目而不是再次创建你的数组。
让我们为此创建一个函数:
pushAt(arr, index, item) {
arr.splice(index, 0, item);
}
现在你可以
ngOnInit() {
Observable.timer(2000).subscribe(() => this.pushAt(this.activeModules, 1, { name: 'Modulo 2' }));
}
编辑 也许您可以尝试使用自定义跟踪功能:
customTrackBy(index, item) { return index; }
在你的HTML
<div *ngFor="let m of activeModules; trackBy: customTrackBy;" [@enterAnimation]>