Angular Lifecycle Hooks: ngOnInit, ngOnDestroy และอื่นๆ ใช้เมื่อไหร่
#angular12 เม.ย. 2569
Lifecycle Hooks คืออะไร
Angular Component มี lifecycle ตั้งแต่สร้างจนถึงทำลาย Angular มี hooks ให้เราเข้าไป execute code ในแต่ละช่วงได้
ลำดับ Lifecycle
ngOnChanges → ngOnInit → ngDoCheck → ngAfterContentInit
→ ngAfterContentChecked → ngAfterViewInit → ngAfterViewChecked
→ ngOnDestroy
ngOnInit — ใช้บ่อยที่สุด
รันหลัง constructor และหลัง input binding ครั้งแรก เหมาะสำหรับดึงข้อมูลจาก API
export class UserComponent implements OnInit {
user: User | null = null;
constructor(private userService: UserService) {}
ngOnInit() {
// ดึงข้อมูลตอน component โหลด
this.userService.getUser(1).subscribe(user => {
this.user = user;
});
}
}
ngOnDestroy — สำคัญมาก
รันก่อน component ถูกทำลาย ใช้สำหรับ unsubscribe เพื่อป้องกัน memory leak
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
export class UserComponent implements OnInit, OnDestroy {
private destroy$ = new Subject<void>();
ngOnInit() {
this.userService.getUsers()
.pipe(takeUntil(this.destroy$))
.subscribe(users => this.users = users);
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
ngOnChanges — รับ Input ที่เปลี่ยน
import { SimpleChanges } from '@angular/core';
export class ChildComponent implements OnChanges {
@Input() userId!: number;
ngOnChanges(changes: SimpleChanges) {
if (changes['userId']) {
const newId = changes['userId'].currentValue;
this.loadUser(newId);
}
}
}
ngAfterViewInit — เข้าถึง DOM
import { AfterViewInit, ElementRef, ViewChild } from '@angular/core';
export class ChartComponent implements AfterViewInit {
@ViewChild('canvas') canvas!: ElementRef;
ngAfterViewInit() {
// DOM พร้อมแล้ว สามารถเข้าถึง canvas ได้
const ctx = this.canvas.nativeElement.getContext('2d');
// วาด chart...
}
}
สรุป
ngOnInit— ดึงข้อมูล, ตั้งค่าเริ่มต้นngOnDestroy— cleanup, unsubscribengOnChanges— react ต่อ Input ที่เปลี่ยนngAfterViewInit— เข้าถึง DOM หลัง render