Bird
Raised Fist0
Angularframework~15 mins

Component lifecycle overview in Angular - Deep Dive

Choose your learning style10 modes available
Overview - Component lifecycle overview
What is it?
In Angular, a component lifecycle is the series of events from when a component is created to when it is destroyed. These events let you run code at specific times, like when the component appears on screen or when its data changes. Understanding this helps you control how your app behaves and responds to user actions. It is like knowing the stages of a plant's life to care for it properly.
Why it matters
Without knowing the component lifecycle, you might run code too early or too late, causing bugs or slow apps. It helps you manage resources, update the screen efficiently, and clean up when a component is no longer needed. This makes your app faster, smoother, and easier to maintain. Imagine trying to water a plant without knowing when it needs water or sunlight—it would not grow well.
Where it fits
Before learning component lifecycle, you should understand basic Angular components and templates. After this, you can learn about Angular services, routing, and state management to build complete apps. Lifecycle knowledge is a foundation for advanced topics like performance optimization and dynamic components.
Mental Model
Core Idea
A component lifecycle is a timeline of key moments when Angular creates, updates, and destroys a component, letting you run code at each moment.
Think of it like...
Think of a component like a theater play actor who has a script with cues: when to enter the stage, when to react to other actors, and when to leave. The lifecycle hooks are the cues telling the actor what to do and when.
┌───────────────┐
│ Component     │
│ Created       │
│ (constructor) │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ OnChanges     │
│ (ngOnChanges) │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ OnInit        │
│ (ngOnInit)    │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ DoCheck       │
│ (ngDoCheck)   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ AfterContent  │
│ Init & Checked│
│ (ngAfterContentInit, ngAfterContentChecked)│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ AfterView     │
│ Init & Checked│
│ (ngAfterViewInit, ngAfterViewChecked)│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Destroy       │
│ (ngOnDestroy) │
└───────────────┘
Build-Up - 6 Steps
1
FoundationWhat is a component lifecycle
🤔
Concept: Introduce the idea that components have a life from creation to destruction.
A component in Angular is like a building block of your app. It is created when needed and removed when not. The lifecycle is the timeline of these events. Angular provides special moments called lifecycle hooks where you can run your own code.
Result
You understand that components are not static but have a flow of events you can tap into.
Understanding that components have a lifecycle helps you know when to run code safely and effectively.
2
FoundationBasic lifecycle hooks explained
🤔
Concept: Learn the main lifecycle hooks and their purpose.
Angular has several hooks like ngOnInit (runs after component creation), ngOnChanges (runs when input data changes), and ngOnDestroy (runs before component removal). These hooks let you initialize data, respond to changes, and clean up resources.
Result
You can identify when to use each hook to control component behavior.
Knowing these hooks prevents common bugs like accessing data too early or forgetting to clean up.
3
IntermediateHow Angular detects changes
🤔Before reading on: do you think Angular automatically updates the screen whenever any data changes, or only at specific times? Commit to your answer.
Concept: Understand Angular's change detection and how it triggers lifecycle hooks.
Angular runs change detection to check if data has changed and updates the view. Hooks like ngOnChanges and ngDoCheck run during this process. ngOnChanges runs when input properties change, while ngDoCheck lets you add custom checks.
Result
You see how Angular keeps the screen in sync with data and how hooks fit into this.
Understanding change detection clarifies why some hooks run often and how to optimize performance.
4
IntermediateContent and view lifecycle hooks
🤔Before reading on: do you think content and view hooks run at the same time or separately? Commit to your answer.
Concept: Learn the difference between content projection and view rendering hooks.
Content hooks (ngAfterContentInit, ngAfterContentChecked) run after projected content is initialized and checked. View hooks (ngAfterViewInit, ngAfterViewChecked) run after the component's own view is initialized and checked. This distinction helps manage complex component structures.
Result
You can control code execution depending on whether it relates to projected content or the component's own template.
Knowing this separation helps avoid timing bugs in nested or projected content scenarios.
5
AdvancedCleaning up with ngOnDestroy
🤔Before reading on: do you think Angular automatically cleans up all resources when a component is destroyed, or do you need to do it manually? Commit to your answer.
Concept: Understand the importance of manual cleanup in ngOnDestroy.
Angular calls ngOnDestroy before removing a component. Here you should unsubscribe from observables, detach event handlers, and release resources. Failing to do so causes memory leaks and unexpected behavior.
Result
You can prevent memory leaks and keep your app healthy by cleaning up properly.
Knowing that Angular does not clean everything automatically prevents subtle bugs and performance issues.
6
ExpertLifecycle hooks and performance optimization
🤔Before reading on: do you think running code in every lifecycle hook is always good for performance, or can it cause slowdowns? Commit to your answer.
Concept: Learn how to use lifecycle hooks wisely to optimize app performance.
Running heavy code in hooks like ngDoCheck or ngAfterViewChecked can slow your app because they run frequently. Use them sparingly and prefer OnPush change detection strategy to reduce unnecessary checks. Also, avoid side effects in hooks that run multiple times.
Result
You can write efficient components that update only when needed, improving user experience.
Understanding the cost of lifecycle hooks helps you write performant Angular apps and avoid common pitfalls.
Under the Hood
Angular creates a component instance and calls its constructor. Then it sets input properties and calls ngOnChanges if inputs changed. Next, it calls ngOnInit once after the first ngOnChanges. During change detection cycles, Angular calls ngDoCheck and other hooks to detect and respond to changes. When content or view is projected or rendered, Angular calls the respective after-content and after-view hooks. Finally, before removing the component, Angular calls ngOnDestroy to allow cleanup.
Why designed this way?
Angular's lifecycle hooks were designed to give developers fine control over component behavior at key moments. This modular approach separates concerns like initialization, change detection, and cleanup. Alternatives like automatic cleanup or no hooks would limit flexibility or cause hidden bugs. The design balances ease of use with power and performance.
┌───────────────┐
│ Constructor   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ ngOnChanges   │
│ (if inputs)  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ ngOnInit      │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Change Detection Cycle │
│ ┌─────────────┐       │
│ │ ngDoCheck   │       │
│ │ ngOnChanges │       │
│ └─────────────┘       │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ ngAfterContentInit    │
│ ngAfterContentChecked │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ ngAfterViewInit       │
│ ngAfterViewChecked    │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ ngOnDestroy   │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: do you think ngOnInit runs every time input properties change? Commit yes or no.
Common Belief:ngOnInit runs every time the component's input properties change.
Tap to reveal reality
Reality:ngOnInit runs only once after the component is created, not on input changes. ngOnChanges runs on input changes.
Why it matters:Confusing these hooks can cause initialization code to run multiple times or miss updates, leading to bugs.
Quick: do you think Angular automatically unsubscribes from observables when a component is destroyed? Commit yes or no.
Common Belief:Angular automatically cleans up all subscriptions and event listeners when a component is destroyed.
Tap to reveal reality
Reality:Angular does not automatically unsubscribe from observables or detach event listeners; you must do this in ngOnDestroy.
Why it matters:Failing to clean up causes memory leaks and unexpected app behavior.
Quick: do you think ngDoCheck is called only once per component lifecycle? Commit yes or no.
Common Belief:ngDoCheck runs only once after component initialization.
Tap to reveal reality
Reality:ngDoCheck runs frequently during every change detection cycle, which can be many times per second.
Why it matters:Misusing ngDoCheck for heavy tasks can severely degrade app performance.
Quick: do you think content and view lifecycle hooks run in any order? Commit yes or no.
Common Belief:Content and view lifecycle hooks run in no particular order and can be mixed.
Tap to reveal reality
Reality:Content hooks run before view hooks in a defined sequence to ensure proper initialization.
Why it matters:Ignoring the order can cause timing bugs when accessing projected content or view elements.
Expert Zone
1
ngAfterContentChecked and ngAfterViewChecked run after every change detection cycle, so avoid heavy logic there to prevent slowdowns.
2
Using OnPush change detection strategy reduces how often lifecycle hooks run, improving performance in large apps.
3
You can combine lifecycle hooks with RxJS operators to manage asynchronous data streams cleanly and avoid manual cleanup.
When NOT to use
Avoid relying on lifecycle hooks for complex state management or business logic; use services or state management libraries instead. Also, do not use lifecycle hooks to manipulate DOM directly; use Angular templates and directives for that.
Production Patterns
In real apps, ngOnInit is used for initialization like fetching data. ngOnDestroy cleans up subscriptions. ngOnChanges handles input updates. Developers use OnPush strategy and avoid heavy code in ngDoCheck and after-check hooks to keep apps fast.
Connections
React component lifecycle
Similar pattern with different hook names and timing
Knowing Angular lifecycle helps understand React's useEffect and other hooks, as both manage component creation, updates, and cleanup.
Operating system process lifecycle
Both have creation, running, and termination phases
Understanding component lifecycle is like understanding how an OS manages processes, which helps grasp resource management and cleanup.
Project management phases
Both follow stages from start to finish with checkpoints
Seeing lifecycle as phases with checkpoints helps plan and control complex tasks, whether in software or projects.
Common Pitfalls
#1Not unsubscribing from observables in ngOnDestroy
Wrong approach:ngOnDestroy() { // forgot to unsubscribe }
Correct approach:ngOnDestroy() { this.subscription.unsubscribe(); }
Root cause:Believing Angular cleans up subscriptions automatically.
#2Running heavy code in ngDoCheck causing slow app
Wrong approach:ngDoCheck() { this.heavyCalculation(); }
Correct approach:ngDoCheck() { // keep light or avoid heavy tasks here }
Root cause:Not realizing ngDoCheck runs very frequently.
#3Using ngOnInit to respond to input changes
Wrong approach:ngOnInit() { this.updateData(this.inputProp); }
Correct approach:ngOnChanges(changes) { if (changes.inputProp) { this.updateData(changes.inputProp.currentValue); } }
Root cause:Confusing ngOnInit with ngOnChanges purpose.
Key Takeaways
Angular components have a lifecycle with specific hooks to run code at key moments from creation to destruction.
Understanding when each lifecycle hook runs helps you initialize data, respond to changes, and clean up resources properly.
Change detection triggers many lifecycle hooks frequently, so use them wisely to avoid performance issues.
Manual cleanup in ngOnDestroy is essential to prevent memory leaks and keep your app healthy.
Advanced use of lifecycle hooks combined with Angular strategies leads to efficient, maintainable applications.

Practice

(1/5)
1. Which Angular lifecycle hook is called once after the component's data-bound properties have been initialized?
easy
A. ngOnInit()
B. ngOnDestroy()
C. ngAfterViewInit()
D. ngDoCheck()

Solution

  1. Step 1: Understand lifecycle hook purpose

    ngOnInit() runs once after Angular sets component input properties.
  2. Step 2: Compare other hooks

    ngOnDestroy() runs before component removal, ngAfterViewInit() after view initialization, ngDoCheck() on every change detection.
  3. Final Answer:

    ngOnInit() -> Option A
  4. Quick Check:

    Initialization hook = ngOnInit() [OK]
Hint: Initialization after inputs = ngOnInit() [OK]
Common Mistakes:
  • Confusing ngOnInit with ngAfterViewInit
  • Thinking ngOnDestroy runs on init
  • Mixing ngDoCheck with ngOnInit
2. Which of the following is the correct syntax to implement the OnDestroy lifecycle hook in an Angular component?
easy
A. class MyComponent implements OnDestroy { ngDestroy() { } }
B. class MyComponent implements OnDestroy { ngOnDestroy() { } }
C. class MyComponent { onDestroy() { } }
D. class MyComponent implements OnDestroy { destroy() { } }

Solution

  1. Step 1: Recall correct method name

    The lifecycle hook method for destruction is ngOnDestroy().
  2. Step 2: Check interface implementation

    Implementing OnDestroy requires defining ngOnDestroy() exactly.
  3. Final Answer:

    class MyComponent implements OnDestroy { ngOnDestroy() { } } -> Option B
  4. Quick Check:

    OnDestroy method = ngOnDestroy() [OK]
Hint: Method name must be ngOnDestroy() exactly [OK]
Common Mistakes:
  • Using wrong method name like ngDestroy or destroy
  • Not implementing the interface
  • Omitting parentheses in method
3. Given this Angular component code snippet, what will be logged to the console when the component is initialized and then destroyed?
export class SampleComponent implements OnInit, OnDestroy {
  ngOnInit() {
    console.log('Init');
  }
  ngOnDestroy() {
    console.log('Destroy');
  }
}
medium
A. Only Destroy
B. Only Init
C. Init followed by Destroy
D. No output

Solution

  1. Step 1: Understand ngOnInit behavior

    ngOnInit() runs once when component initializes, logging 'Init'.
  2. Step 2: Understand ngOnDestroy behavior

    ngOnDestroy() runs once before component is removed, logging 'Destroy'.
  3. Final Answer:

    Init followed by Destroy -> Option C
  4. Quick Check:

    Init then Destroy logs = Init followed by Destroy [OK]
Hint: Init logs on start, Destroy logs on removal [OK]
Common Mistakes:
  • Assuming ngOnDestroy runs on init
  • Expecting logs in reverse order
  • Thinking no logs appear
4. Identify the error in this Angular component lifecycle hook implementation:
export class TestComponent implements OnInit {
  ngOnInit() {
    console.log('Component initialized');
  }
  ngOnDestroy() {
    console.log('Component destroyed');
  }
}
medium
A. Missing OnDestroy interface in implements clause
B. ngOnInit method name is incorrect
C. ngOnDestroy should not be used here
D. Console.log statements are invalid

Solution

  1. Step 1: Check implemented interfaces

    The class implements OnInit but defines ngOnDestroy() without implementing OnDestroy.
  2. Step 2: Understand interface contract

    To use ngOnDestroy(), the class should implement OnDestroy interface for clarity and correctness.
  3. Final Answer:

    Missing OnDestroy interface in implements clause -> Option A
  4. Quick Check:

    Implement interface for each lifecycle hook used [OK]
Hint: Implement interfaces for all lifecycle hooks used [OK]
Common Mistakes:
  • Ignoring interface implementation for ngOnDestroy
  • Thinking method names are wrong
  • Believing console.log is invalid
5. You want to run code after Angular fully initializes the component's view and its child views. Which lifecycle hook should you use, and why? Choose the correct hook and reason.
hard
A. ngAfterContentInit() because it runs after projected content is initialized.
B. ngOnInit() because it runs after input properties are set.
C. ngDoCheck() because it runs on every change detection cycle.
D. ngAfterViewInit() because it runs after the component's view and child views are initialized.

Solution

  1. Step 1: Identify hook for view initialization

    ngAfterViewInit() runs after Angular initializes the component's view and child views.
  2. Step 2: Compare other hooks

    ngOnInit() runs earlier, ngAfterContentInit() runs after projected content, and ngDoCheck() runs repeatedly.
  3. Final Answer:

    ngAfterViewInit() because it runs after the component's view and child views are initialized. -> Option D
  4. Quick Check:

    View init completion = ngAfterViewInit() [OK]
Hint: Use ngAfterViewInit() for post-view initialization code [OK]
Common Mistakes:
  • Confusing ngAfterContentInit with ngAfterViewInit
  • Using ngOnInit for view-dependent code
  • Expecting ngDoCheck to run once
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard