Angular Animations: สร้าง Animation ด้วย @angular/animations
#angular12 เม.ย. 2569
Angular Animations คืออะไร
Angular มี animation system ในตัวที่ใช้ CSS transitions และ Web Animations API ช่วยให้สร้าง animation ได้โดยไม่ต้องเขียน CSS เอง
ติดตั้ง
// main.ts
import { provideAnimations } from '@angular/platform-browser/animations';
bootstrapApplication(AppComponent, {
providers: [provideAnimations()]
});
Animation พื้นฐาน
import {
trigger, state, style, animate, transition
} from '@angular/animations';
@Component({
animations: [
trigger('fadeInOut', [
state('void', style({ opacity: 0 })),
transition(':enter', [
animate('300ms ease-in', style({ opacity: 1 }))
]),
transition(':leave', [
animate('300ms ease-out', style({ opacity: 0 }))
])
])
],
template: `
<div *ngIf="show" @fadeInOut>
เนื้อหาที่ fade in/out
</div>
`
})
export class MyComponent {
show = true;
}
Slide Animation
trigger('slideDown', [
transition(':enter', [
style({ height: 0, overflow: 'hidden' }),
animate('300ms ease-out', style({ height: '*' }))
]),
transition(':leave', [
animate('300ms ease-in', style({ height: 0, overflow: 'hidden' }))
])
])
State Animation
trigger('buttonState', [
state('normal', style({ backgroundColor: '#1976d2', transform: 'scale(1)' })),
state('active', style({ backgroundColor: '#e91e63', transform: 'scale(1.1)' })),
transition('normal <=> active', animate('200ms ease-in-out'))
])
<button [@buttonState]="isActive ? 'active' : 'normal'"
(click)="isActive = !isActive">
Click me
</button>
Stagger Animation
import { query, stagger } from '@angular/animations';
trigger('listAnimation', [
transition('* => *', [
query(':enter', [
style({ opacity: 0, transform: 'translateY(-20px)' }),
stagger(100, [
animate('300ms', style({ opacity: 1, transform: 'translateY(0)' }))
])
], { optional: true })
])
])
สรุป
Angular Animations ช่วยให้สร้าง animation ที่ smooth และ performant ได้ง่าย ควรใช้อย่างพอดีเพื่อไม่ให้ UX แย่ลงครับ