Các hook hay gặp: ngOnChanges chạy khi input đổi, lần đầu chạy trước ngOnInit; ngOnInit chạy một lần sau khi input initial xong; ngAfterViewInit dùng khi view/query đã sẵn sàng; ngOnDestroy hoặc DestroyRef dùng cleanup.
Ví dụ cleanup hiện đại:
@Component({ template: "{{ userId() }}" })
export class UserPage {
userId = input.required<string>()
constructor() {
inject(DestroyRef).onDestroy(() => console.log("cleanup"))
}
}Từ Angular hiện đại, afterNextRender/afterEveryRender phù hợp cho DOM work sau render và không chạy trong SSR/prerender.
Common hooks: ngOnChanges runs when inputs change and its first run happens before ngOnInit; ngOnInit runs once after initial inputs are set; ngAfterViewInit is for ready view/query state; ngOnDestroy or DestroyRef is for cleanup.
Modern cleanup example:
@Component({ template: "{{ userId() }}" })
export class UserPage {
userId = input.required<string>()
constructor() {
inject(DestroyRef).onDestroy(() => console.log("cleanup"))
}
}In modern Angular, afterNextRender/afterEveryRender fit DOM work after rendering and do not run during SSR/prerender.