Angular 5 Animation 为 ngFor 中的多个列表项运行

标签 angular

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

但是,动画正在为所有元素运行。是否可以只在移除的项目上运行动画。

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,因为每次列表更改后它都会更新。

ma​​in.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 做到这一点。

ma​​in.component.ts

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

ma​​in.component.html

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

关于Angular 5 Animation 为 ngFor 中的多个列表项运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48033098/

相关文章:

angular - 在基于 session 的 cookie Angular 6 中存储 JWT

angular - D3.js V4 和 Angular 不会发生节点转换

Angular 2 输入指令修改表单控件值

Angular 2 本地主机和后端服务器连接

Angular 2 : Error: TypeError: Cannot read property '...' of undefined

typescript - Angular 2 FormBuilder 实例化期间出现错误

javascript - 如何将ISO8601 json转换为正常日期格式

javascript - 如何使用 Angular 4 禁用 Angular CLI 中的默认捆绑

Angular 4 动态表单 : Dependent Dropdown

Angular 应用程序使用 PKCE 登录到 cognito,然后调用我的 API