Skip to solution
mediumFrontend

What are Angular lifecycle hooks?

935 views
01

Understand the problem

Name the key lifecycle hooks and when they run.

lifecycle
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Hooks let you tap into a component's life: ngOnChanges (input changes), ngOnInit (after first inputs set), ngDoCheck, ngAfterContentInit/Checked, ngAfterViewInit/Checked, and ngOnDestroy (cleanup, unsubscribe). ngOnInit is the usual place for initialization that needs inputs.

Solution ready — 2 min read

Classified // press E to declassify

04

Read the code

Common hooks
import { Component, Input, OnInit, OnChanges, OnDestroy, SimpleChanges } from '@angular/core';

@Component({ selector: 'app-user', standalone: true, template: '{{ id }}' })
export class UserComponent implements OnInit, OnChanges, OnDestroy {
  @Input() id!: number;
  private timer?: any;

  ngOnChanges(c: SimpleChanges) { /* runs when 'id' changes */ }
  ngOnInit() { this.timer = setInterval(() => {}, 1000); }   // setup
  ngOnDestroy() { clearInterval(this.timer); }               // cleanup → no leak
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 26 of 121 decoded in the Angular track. One more won't hurt.

Back to track