In Angular, you can animate list items when they are added or removed using Angular Animations (@angular/animations) with @trigger.
1. Import Required Modules (in app.module.ts)
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
imports: [BrowserAnimationsModule],
})
export class AppModule {}
2. Define Animation in Component (list.component.ts)
import { Component } from '@angular/core';
import { trigger, transition, style, animate } from '@angular/animations';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
animations: [
trigger('listAnimation', [
transition(':enter', [
style({ opacity: 0, transform: 'translateY(-10px)' }),
animate('300ms ease-out', style({ opacity: 1, transform: 'translateY(0)' }))
]),
transition(':leave', [
animate('300ms ease-in', style({ opacity: 0, transform: 'translateY(10px)' }))
])
])
]
})
export class ListComponent {
items: string[] = [];
addItem() { this.items.push(`Item ${this.items.length + 1}`); }
removeItem(index: number) { this.items.splice(index, 1); }
}
3. Apply Animation in Template (list.component.html)
<button (click)="addItem()">Add Item</button>
<ul>
<li *ngFor="let item of items; let i = index" @listAnimation>
{{ item }} <button (click)="removeItem(i)">Remove</button>
</li>
</ul>