0
0
Angularframework~15 mins

Lifecycle execution order mental model in Angular - Deep Dive

Choose your learning style9 modes available
Overview - Lifecycle execution order mental model
What is it?
In Angular, components and directives go through a series of steps called lifecycle hooks. These hooks are special methods that run automatically at specific moments, like when a component is created, updated, or destroyed. Understanding the order of these hooks helps you control how your app behaves over time. It’s like knowing the stages of a plant’s growth to care for it properly.
Why it matters
Without knowing the lifecycle order, developers might run code too early or too late, causing bugs or poor user experience. For example, trying to access data before it’s ready or cleaning up too late can slow down or break the app. Knowing the lifecycle order lets you write code that fits perfectly into Angular’s flow, making apps faster, smoother, and easier to maintain.
Where it fits
Before learning lifecycle order, you should understand Angular components and templates basics. After mastering lifecycle hooks, you can learn advanced topics like change detection, performance optimization, and reactive programming with RxJS.
Mental Model
Core Idea
Angular lifecycle hooks run in a fixed sequence that mirrors a component’s birth, growth, updates, and death, letting you insert code at the right moment.
Think of it like...
Think of an Angular component like a play: first the actors prepare backstage (creation hooks), then perform scenes (update hooks), and finally take a bow and leave the stage (destruction hooks). Each lifecycle hook is a cue for a specific part of the show.
┌───────────────┐
│ Component Born│
│ (constructor) │
└──────┬────────┘
       │
┌──────▼────────┐
│ ngOnChanges   │
│ (input change)│
└──────┬────────┘
       │
┌──────▼────────┐
│ ngOnInit      │
│ (init logic)  │
└──────┬────────┘
       │
┌──────▼────────┐
│ ngDoCheck    │
│ (custom check)│
└──────┬────────┘
       │
┌──────▼────────┐
│ ngAfterContent│
│ Init & Checked│
└──────┬────────┘
       │
┌──────▼────────┐
│ ngAfterView   │
│ Init & Checked│
└──────┬────────┘
       │
┌──────▼────────┐
│ Component Live│
│ (updates)     │
└──────┬────────┘
       │
┌──────▼────────┐
│ ngOnDestroy   │
│ (cleanup)    │
└──────────────┘
Build-Up - 7 Steps
1
FoundationWhat are Angular lifecycle hooks
🤔
Concept: Introduce lifecycle hooks as special methods Angular calls at key moments in a component's life.
Angular components have built-in methods called lifecycle hooks. These hooks run automatically when something important happens, like when the component is created, updated, or destroyed. Examples include ngOnInit, ngOnChanges, and ngOnDestroy.
Result
Learners understand that lifecycle hooks are automatic callbacks tied to component events.
Understanding lifecycle hooks is the first step to controlling when your code runs in Angular.
2
FoundationBasic lifecycle hook sequence overview
🤔
Concept: Explain the general order in which Angular calls lifecycle hooks during component creation and destruction.
When Angular creates a component, it calls hooks in this order: constructor, ngOnChanges (if inputs exist), ngOnInit, ngDoCheck, ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked. When the component is removed, ngOnDestroy runs.
Result
Learners see the full lifecycle path from creation to destruction.
Knowing the sequence helps predict when to place initialization or cleanup code.
3
IntermediateRole of ngOnChanges and input updates
🤔Before reading on: do you think ngOnChanges runs only once or multiple times during a component's life? Commit to your answer.
Concept: Show how ngOnChanges runs every time input properties change, not just at creation.
ngOnChanges runs whenever Angular detects a change in input properties from a parent component. This can happen multiple times, allowing you to react to new data. It runs before ngOnInit on the first change.
Result
Learners understand ngOnChanges is for reacting to input changes anytime.
Recognizing ngOnChanges runs multiple times prevents bugs from assuming inputs never change after init.
4
IntermediateDifference between ngOnInit and constructor
🤔Before reading on: do you think constructor or ngOnInit is better for fetching data? Commit to your answer.
Concept: Clarify that constructor is for setup, ngOnInit is for initialization that needs Angular bindings ready.
The constructor runs first but should only set up basic things. ngOnInit runs after Angular sets input properties, so it's safe to access inputs or start fetching data there. Using constructor for data fetch can cause errors because inputs may not be ready.
Result
Learners know to use ngOnInit for initialization that depends on inputs.
Separating setup and initialization avoids timing bugs and improves code clarity.
5
IntermediateCustom change detection with ngDoCheck
🤔Before reading on: do you think Angular always detects all changes automatically? Commit to your answer.
Concept: Introduce ngDoCheck as a hook to detect changes Angular might miss.
Angular's default change detection checks many changes, but sometimes you need to detect complex or manual changes. ngDoCheck runs frequently and lets you write custom logic to detect and react to changes Angular doesn't catch automatically.
Result
Learners see how to extend Angular's change detection for special cases.
Knowing ngDoCheck exists helps handle tricky update scenarios without hacks.
6
AdvancedAfterContent and AfterView hooks explained
🤔Before reading on: do you think content and view hooks run once or multiple times? Commit to your answer.
Concept: Explain the difference between content projection and view rendering hooks and their timing.
ngAfterContentInit and ngAfterContentChecked run after projected content (like ) is initialized and checked. ngAfterViewInit and ngAfterViewChecked run after the component's own view and child views are initialized and checked. These hooks run once after init and then after every change detection cycle.
Result
Learners understand when to access projected content and child views safely.
Distinguishing content vs. view hooks prevents accessing DOM too early or too late.
7
ExpertLifecycle hooks and change detection interplay
🤔Before reading on: do you think lifecycle hooks trigger change detection or just respond to it? Commit to your answer.
Concept: Reveal how lifecycle hooks fit into Angular's change detection cycle and how they can trigger or respond to it.
Angular runs change detection to update the UI. Lifecycle hooks like ngAfterViewChecked run after change detection completes. Some hooks can trigger additional change detection cycles if they update data, which can cause infinite loops if not careful. Understanding this interplay helps optimize performance and avoid bugs.
Result
Learners grasp the delicate timing between hooks and change detection.
Knowing how hooks and change detection interact is key to writing efficient, bug-free Angular apps.
Under the Hood
Angular creates components by calling the constructor first, then sets input properties. It then calls lifecycle hooks in a fixed order during the change detection process. Change detection runs frequently to check for data changes and update the UI. Hooks like ngOnChanges detect input changes, while others like ngAfterViewInit run after Angular renders the component's view. Angular uses a zone to detect async events and trigger change detection automatically.
Why designed this way?
Angular's lifecycle hooks were designed to give developers precise control over component behavior at key moments, balancing automatic UI updates with manual intervention. The fixed order ensures predictable timing, while hooks like ngDoCheck allow customization. This design avoids forcing developers to write complex timing code and supports efficient UI updates.
┌───────────────┐
│ Constructor   │
└──────┬────────┘
       │
┌──────▼────────┐
│ Set Inputs    │
└──────┬────────┘
       │
┌──────▼────────┐
│ ngOnChanges   │
└──────┬────────┘
       │
┌──────▼────────┐
│ ngOnInit      │
└──────┬────────┘
       │
┌──────▼────────┐
│ ngDoCheck     │
└──────┬────────┘
       │
┌──────▼────────┐
│ ngAfterContent│
│ Init & Check  │
└──────┬────────┘
       │
┌──────▼────────┐
│ ngAfterView   │
│ Init & Check  │
└──────┬────────┘
       │
┌──────▼────────┐
│ Change Detect │
│ Cycle Ends    │
└──────┬────────┘
       │
┌──────▼────────┐
│ ngOnDestroy   │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does ngOnInit run before or after the first ngOnChanges? Commit to your answer.
Common Belief:ngOnInit runs before ngOnChanges because it sounds like initialization comes first.
Tap to reveal reality
Reality:ngOnChanges runs before ngOnInit on the first change detection cycle if there are input properties.
Why it matters:Assuming ngOnInit runs first can cause missing input changes and bugs in initialization logic.
Quick: Do you think the constructor is a good place to access input properties? Commit to your answer.
Common Belief:The constructor is where you should access inputs and start data fetching.
Tap to reveal reality
Reality:Input properties are not set when the constructor runs; they are set afterward, so accessing them in the constructor gives undefined or wrong values.
Why it matters:Using inputs too early leads to errors and unpredictable behavior.
Quick: Does ngDoCheck always run only once per lifecycle? Commit to your answer.
Common Belief:ngDoCheck runs once like other hooks during initialization.
Tap to reveal reality
Reality:ngDoCheck runs many times during every change detection cycle, allowing custom change detection logic.
Why it matters:Misunderstanding this can cause performance issues if heavy logic is placed inside ngDoCheck.
Quick: Can lifecycle hooks trigger infinite loops if misused? Commit to your answer.
Common Belief:Lifecycle hooks just respond to changes and cannot cause loops.
Tap to reveal reality
Reality:If a hook updates data that triggers change detection again, it can cause infinite loops.
Why it matters:Not knowing this can crash apps or freeze the UI.
Expert Zone
1
ngAfterContentInit and ngAfterViewInit run only once after initialization, but their Checked counterparts run after every change detection cycle, which can impact performance if misused.
2
Using ngDoCheck requires careful optimization because it runs frequently; heavy computations here can degrade app responsiveness.
3
The constructor is a pure TypeScript class constructor and runs before Angular sets inputs or runs change detection, so it should never contain Angular-specific logic.
When NOT to use
Avoid relying on lifecycle hooks for complex state management or asynchronous data flows; instead, use reactive patterns with RxJS and Angular's async pipe for cleaner, more maintainable code.
Production Patterns
In real apps, ngOnInit is used for initial data loading, ngOnDestroy for cleanup like unsubscribing from observables, and ngOnChanges to react to input changes. Advanced apps use ngDoCheck sparingly for performance tuning and custom change detection.
Connections
React component lifecycle
Similar pattern of lifecycle hooks for managing component creation, updates, and destruction.
Understanding Angular lifecycle helps grasp React’s useEffect and other hooks, as both manage component timing and side effects.
Event-driven programming
Lifecycle hooks are event callbacks triggered by Angular’s internal events during component life.
Knowing event-driven patterns clarifies why lifecycle hooks exist and how they fit into reactive UI updates.
Human project management phases
Lifecycle hooks mirror phases like planning, execution, review, and closure in projects.
Seeing lifecycle hooks as project phases helps understand the importance of timing and order in managing complex tasks.
Common Pitfalls
#1Trying to access input properties in the constructor.
Wrong approach:constructor() { console.log(this.inputProp); }
Correct approach:ngOnInit() { console.log(this.inputProp); }
Root cause:Inputs are not set when the constructor runs, so accessing them there gives undefined.
#2Updating component data inside ngAfterViewChecked without checks.
Wrong approach:ngAfterViewChecked() { this.count++; }
Correct approach:ngAfterViewChecked() { if (this.countNeedsUpdate) { this.count++; this.countNeedsUpdate = false; } }
Root cause:Updating data unconditionally in this hook triggers infinite change detection loops.
#3Heavy computations inside ngDoCheck.
Wrong approach:ngDoCheck() { this.expensiveCalculation(); }
Correct approach:ngDoCheck() { if (this.shouldRecalculate) { this.expensiveCalculation(); } }
Root cause:ngDoCheck runs very often; heavy work here slows the app.
Key Takeaways
Angular lifecycle hooks run in a specific order that reflects a component’s creation, update, and destruction phases.
ngOnChanges runs whenever input properties change, often multiple times, and always before ngOnInit on first change.
The constructor is for basic setup only; initialization depending on inputs belongs in ngOnInit.
Hooks like ngDoCheck and after-content/view hooks allow fine control but must be used carefully to avoid performance issues.
Understanding lifecycle hooks deeply helps write predictable, efficient, and bug-free Angular applications.