Lifecycle Hooks — Angular Technical Interview Questions & Answers

Lifecycle Hooks

Lifecycle Hooks

  • ngOnInit runs once after inputs are set — load marks here, not in the constructor. ngOnDestroy — stop timers, unsubscribe. ngOnChanges — when @Input changes.
  • Board: constructor only assigns. ngOnInit calls marksService.list(). ngOnDestroy clears a setInterval. Trap: HTTP in constructor — inputs may still be undefined.

Technical Interview Tip: Init vs constructor. Destroy cleanup.

Code Examples for Lifecycle Hooks

Lifecycle Hooks — working example

import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  template: `
    <h1>{{ title }}</h1>
    <button (click)="toggle()">Toggle</button>
    <p *ngIf="open">Panel open</p>
  `,
})
export class AppComponent {
  title = "Angular practice";
  open = true;
  toggle() {
    this.open = !this.open;
  }
}

Lifecycle Hooks: toggle open. Say whether the panel is on screen after one click.

How to Explain Lifecycle Hooks to an Interviewer

ngOnInit vs constructor?

Init: inputs ready, load data Constructor: only assign

Why ngOnDestroy?

Clear timers / unsubscribe