🧩 What Is the Angular Lifecycle?
Every Angular component (or directive) goes through a series of stages:
-
Creation
-
Change detection & rendering
-
Updates when data changes
-
Cleanup when the component is removed
Angular provides lifecycle hooks—special methods you can add to your component class to run code at each stage.
📜 The Full Lifecycle Order
Below is the order Angular calls these hooks, plus what they’re for:
Hook | When It Runs | Why/What to Do |
---|---|---|
constructor (not a hook, but first) | When the component class is instantiated (before Angular sets input properties). | Only lightweight setup—don’t rely on @Input() values yet. |
ngOnChanges(changes) | Every time an @Input property changes (called first, even before ngOnInit ). | React to input property changes. |
ngOnInit() | Called once after the first ngOnChanges . | Good place for initial data loading (HTTP calls, set up state). |
ngDoCheck() | Called on every Angular change-detection run (often). | Custom change detection beyond Angular’s default. |
ngAfterContentInit() | After Angular projects external content into the component’s <ng-content> . | Run logic that depends on projected content. |
ngAfterContentChecked() | After every check of projected content. | Respond if that content changes. |
ngAfterViewInit() | After the component’s view (and child views) are fully initialized. | Safely access @ViewChild elements or DOM. |
ngAfterViewChecked() | After every check of the component’s view. | Rarely needed; respond to view changes. |
ngOnDestroy() | Right before Angular removes the component. | Cleanup: unsubscribe from Observables, stop timers, detach event listeners. |
📊 Visual Flow
🛠️ Example Component
Check the browser console to see the call order in real time.
🏆 Best Practices
-
Initialize data in
ngOnInit
, not the constructor. -
Clean up in
ngOnDestroy
(unsubscribe Observables, clear intervals). -
Use
ngOnChanges
to react to input property changes. -
Use view-related hooks (
ngAfterViewInit
) only when you need direct DOM access.
🏁 Quick Recap
Angular’s component lifecycle is a sequence:
-
Create → constructor, ngOnChanges, ngOnInit
-
Check & update → ngDoCheck, ngAfterContent*/View* hooks
-
Destroy → ngOnDestroy for cleanup.
Knowing these hooks helps you load data at the right time, manage resources, and avoid memory leaks in any Angular application.
No comments:
Post a Comment