Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 Animation runs for multiple list items inside ngFor

Tags:

angular

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)' })),
        ])
    ])
])

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>
like image 438
Sahin Erbay Avatar asked Jan 29 '26 17:01

Sahin Erbay


1 Answers

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>
like image 87
Sahin Erbay Avatar answered Jan 31 '26 11:01

Sahin Erbay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!