Angular 5 Animation在ngFor中针对多个列表项运行 [英] Angular 5 Animation runs for multiple list items inside ngFor

查看:37
本文介绍了Angular 5 Animation在ngFor中针对多个列表项运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 productsItems 数组,该数组通过Input()来自父元素,我想在动画被删除时在每个元素上添加动画.

I have a productsItems array which is coming from a parent element via Input() and I would like to add the animation on each element when it's removed.

但是,动画正在针对所有元素运行.是否可以仅在已删除项目上运行动画.

However, the animation is running for all the elements. Is it possible to run the animation only on the removed item.

animation.ts

 import { trigger, state, animate, transition, style, sequence } from 
'@angular/animations';

export const SlideToggleAnimation =
trigger('slideState', [
    state('show', style({
        opacity: 1,
        visibility: 'visible'
    })),
    state('hide', style({
        opacity: 0,
        visibility: 'hidden'
    })),
    transition('show => hide', animate('300ms ease-out')),
    transition('hide => show', animate('300ms ease-in')),

    transition('* => void', [
        style({ height: '*', opacity: '1', transform: 'translateX(0)', 'box-shadow': '0 1px 4px 0 rgba(0, 0, 0, 0.3)' }),
        sequence([
            animate(".25s ease", style({ height: '*', opacity: '.2', transform: 'translateX(20px)', 'box-shadow': 'none' })),
            animate(".1s ease", style({ height: '0', opacity: 0, transform: 'translateX(20px)', 'box-shadow': 'none' }))
        ])
    ]),
    transition('void => *', [
        style({ opacity: '0', transform: 'translateX(20px)' }),
        sequence([
            animate(".2s ease", style({ opacity: '1', transform: 'translateX(2px)' })),
        ])
    ])
])

我通过output()检测到删除按钮的动作,并使用它来确定动画的状态.发生这种情况是因为 productItems ,因为列表更改后每次都会更新.

I detect the remove button actions via output() and use it to determine the state of the animation. Is this happening because the productItems, since it's updating every time after the list is changed.

main.component.ts

<li class="shopping-cart__item" *ngFor="let product of productsItems" 
[@slideState]="product.isRemoved ? 'hide' : 'show'" 
(@slideState.start)="animStart($event)" 
(@slideState.done)="animEnd($event)">
....
<app-remove-button [productId]="product._id" (isRemoved)="onRemove($event)" appDeleteIconHover></app-remove-button>
</li>

推荐答案

我能够通过trackBy做到这一点.

I was able to do this via trackBy.

main.component.ts

trackByProductId(index: number, product: any): string {
    return product._id;
}

main.component.html

<li class="shopping-cart__item" 
 *ngFor="let product of productsItems;  
  trackBy:trackByProductId" [@slideState]="product">
   ...
   ...
 </li>

这篇关于Angular 5 Animation在ngFor中针对多个列表项运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆