Component lifecycle hooks

Intermediate · 10 min

The fixed sequence of moments every component passes through, and which hook to use for each one.

Before thisComponent basics and the @Component decorator

CodingForBeginners · 10 min

Component lifecycle hooks

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodingForBeginnersReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A component's constructor runs before Angular has set its `@Input()` values — reading an input there gets you `undefined`, not the real value.
  • `ngOnInit` runs once, after the first round of inputs are set, which is why it — not the constructor — is where real initialization logic belongs.
  • `ngOnChanges` fires on every input change after the first, which makes it the only hook that tells you specifically what changed and what it changed from.

A component’s life isn’t instantaneous

A component isn’t just “there” or “not there.” It gets constructed, has its inputs set, gets attached to the DOM, potentially gets its inputs changed again later, and eventually gets torn down. Those are genuinely different moments — code that’s correct for “right after construction” is often wrong for “after the DOM exists,” and code that’s fine for “runs once” is wrong for “needs to run every time an input changes.” A framework that only gave you a constructor would be forcing every one of those distinct moments through a single, badly-fitting door.

Angular’s answer is a fixed, documented sequence of moments, and a named method — a lifecycle hook — for each one you might need to act on.

The constructor is not where initialization logic goes

This is the single most common beginner mistake, and it comes from a reasonable assumption: “the constructor runs first, so that’s where I set things up.” For a component with @Input() properties, that assumption is wrong, because of the order Angular actually follows:

  1. The class constructor runs.
  2. Angular sets the component’s @Input() properties from what the parent bound.
  3. ngOnInit runs.

Read a bound input inside the constructor and you get undefined — the property assignment in step 2 hasn’t happened yet. That’s not a quirk to work around; it’s the reason ngOnInit exists as a separate hook. Constructor logic in Angular should be limited to what dependency injection gives you (injected services), not anything derived from inputs. Real setup work — fetching data based on an input, computing a derived value — belongs in ngOnInit.

ngOnChanges: the hook that tells you what changed

ngOnInit runs once. But inputs can change again later — a parent re-renders a list and now your component is showing a different item, for instance — and ngOnInit won’t fire again for that. ngOnChanges will, every time, and it’s the only hook that hands you a SimpleChanges object describing exactly what changed:

ngOnChanges(changes: SimpleChanges) {
  if (changes['userId']) {
    console.log('was', changes['userId'].previousValue, 'now', changes['userId'].currentValue);
  }
}

If all you need is “do something whenever this one input changes,” a computed signal or an effect (covered in a later lesson) is often a more direct tool. But when you genuinely need the before-and-after values of a change, or need to react to several inputs changing together, ngOnChanges is built for exactly that in a way nothing else in Angular’s template-input system is.

The hooks that bracket rendering, and the one that cleans up

A handful of other hooks round out the full sequence: ngAfterViewInit fires once the component’s own view — and any child components inside it — have finished initializing, which matters when you need to act on something only available after rendering (measuring an element’s size, for instance). ngAfterContentInit is its cousin for projected content rather than the component’s own view. And ngOnDestroy fires right before Angular removes the component — the one hook that exists specifically for cleanup: unsubscribing from an observable you manually subscribed to, clearing an interval, detaching an event listener you added outside Angular’s own binding system. Skip it and you’ve built a memory leak that only shows up once users navigate away and back enough times to notice.

This lesson’s video runs through the hooks in execution order with a live example — watch for the console-log order it produces, since seeing the sequence happen is more convincing than reading it described. The linked “deeper” video focuses specifically on ngOnDestroy and the cleanup habit worth building around it.

Where this comes back later

Subscription cleanup is exactly the problem ngOnDestroy exists to solve, and it’s also exactly the problem the RxJS section of this roadmap spends real time on — once you’ve seen takeUntilDestroyed and the async pipe’s automatic unsubscription, you’ll have a second, often better tool for the same job ngOnDestroy currently has to do by hand.

Check yourself

  1. 01Why does code that reads `this.userId` inside a component's constructor often see `undefined`, even though a parent template passes `[userId]="123"`?

    Angular constructs the component instance, then sets its `@Input()` properties afterward, then calls `ngOnInit`. The constructor runs before that input assignment happens, so any input read there hasn't been set yet. Move that logic into `ngOnInit` and the value is there.

  2. 02You need to re-fetch data whenever a component's `userId` input changes, after the component has already been showing a different user. Which lifecycle hook is built for exactly this?

    `ngOnChanges`. It fires any time a bound input changes — not just on the first set — and receives a `SimpleChanges` object telling you which inputs changed and what their previous and current values were, which is exactly what a re-fetch-on-change needs.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark