Services & RoutingExtra· 35 min read

Component Lifecycle Hooks

Angular runs your code at key moments in a component’s life — like the moment it is born (ngOnInit) and the moment it is destroyed (ngOnDestroy).

What you will learn

  • Explain what a lifecycle hook is
  • Use ngOnInit to load data when a component starts
  • Use ngOnDestroy to clean up before it leaves

A component has a life story

Every component goes through a lifecycle: Angular creates it, shows it, updates it as data changes, and finally destroys it when you navigate away. A lifecycle hook is a method you add to the class that Angular calls automatically at one of those moments — your chance to run code at exactly the right time.

You implement a hook by adding a method with a special name. The two you will use constantly are ngOnInit (just after the component is created) and ngOnDestroy (just before it is removed).

HookRuns when…Common use
ngOnChangesan @Input value changesReact to new input data
ngOnInitonce, after the component is createdLoad data, set things up
ngAfterViewInitonce, after the template is readyTouch DOM elements, focus an input
ngOnDestroyjust before the component is removedClean up: unsubscribe, clear timers

ngOnInit: set up when the component starts

A common beginner question is “why not just put setup in the constructor?” The constructor is for receiving injected services, but the component is not fully ready yet — inputs may not be set. ngOnInit runs a moment later, once everything is in place, so it is the right home for loading data.

ngOnInit loads data after the component is created
// tasks.component.ts
import { Component, OnInit } from '@angular/core';
import { TaskService } from './task.service';

@Component({ selector: 'app-tasks', standalone: true, template: '...' })
export class TasksComponent implements OnInit {
  tasks: any[] = [];

  constructor(private taskService: TaskService) {}

  ngOnInit() {
    this.tasks = this.taskService.getTasks();   // load when ready
  }
}

Note: Output: (Tasks appear as soon as the component shows.) Angular calls ngOnInit once, right after creating the component, so the tasks load at the perfect moment. The implements OnInit part is a TypeScript hint that makes the editor check you spelled the method correctly.

ngOnDestroy: clean up before you leave

When a component is removed (for example you navigate to another page), Angular calls ngOnDestroy. This is where you clean up anything that would otherwise keep running in the background — a timer, or a subscription (you will meet subscriptions in the RxJS lesson). Forgetting this causes memory leaks, where old code keeps running invisibly.

ngOnDestroy stops a timer before the component leaves
import { Component, OnDestroy } from '@angular/core';

export class ClockComponent implements OnDestroy {
  private timerId = setInterval(() => console.log('tick'), 1000);

  ngOnDestroy() {
    clearInterval(this.timerId);   // stop the timer on the way out
  }
}

Note: Output: tick tick tick … (then it stops) The timer logs “tick” every second while the component is on screen. When you navigate away, ngOnDestroy runs clearInterval and the ticking stops — no leftover timer eating resources.

  1. Angular creates the component and runs its constructor (services are injected here).
  2. If it has inputs, ngOnChanges runs with the first values.
  3. ngOnInit runs once — load data and finish setup here.
  4. The template renders; ngAfterViewInit runs once the view exists.
  5. While alive, ngOnChanges runs again whenever an input changes.
  6. When removed, ngOnDestroy runs — clean up timers and subscriptions.

Watch out: Do not do heavy work or data loading in the constructor. Use ngOnInit — by then the component is fully built and its inputs are set, so your code behaves predictably.

Tip: The two hooks you will use 90% of the time are ngOnInit (start things) and ngOnDestroy (stop things). Learn these two first; the others come up as you need them.

Q. Which lifecycle hook is the recommended place to load a component’s initial data?

Answer: ngOnInit runs once just after the component is created and its inputs are set — the ideal spot for initial data loading. The constructor should only receive injected dependencies.

✍️ Practice

  1. Add ngOnInit to a component that logs “component ready” when it appears.
  2. Add ngOnDestroy that logs “goodbye” and route away to see it run.

🏠 Homework

  1. Build a component with a setInterval counter started in ngOnInit and cleared in ngOnDestroy, and confirm it stops when you navigate away.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →