MyInternships.in

Directives, Pipes & Templates

Angular Lifecycle Hooks

Lifecycle hooks are methods Angular calls at defined moments in a component’s life — creation, input changes, view initialisation and destruction. Implementing them lets you run setup and teardown at exactly the right time.


What is Lifecycle Hooks in Angular?

Lifecycle hooks are methods Angular calls at defined moments in a component’s life — creation, input changes, view initialisation and destruction. Implementing them lets you run setup and teardown at exactly the right time.

Lifecycle Hooks example

The two you will use most
TypeScript
export class JobListComponent implements OnInit, OnDestroy {
  private sub?: Subscription;

  ngOnInit(): void {
    this.sub = this.api.getJobs().subscribe(jobs => (this.jobs = jobs));
  }

  ngOnDestroy(): void {
    this.sub?.unsubscribe();
  }
}

Key points to remember

  • Use the constructor only for dependency injection; put real work in ngOnInit.
  • ngOnDestroy is where memory leaks are prevented — unsubscribe everything you subscribed manually.
  • The async pipe removes most manual subscription management entirely.

The hooks in call order

HookWhen it runsTypical use
ngOnChangesbefore ngOnInit and on every input changereact to a changed @Input
ngOnInitonce, after the first ngOnChangesfetch data, set up subscriptions
ngDoCheckevery change detection cyclecustom change detection (rare)
ngAfterContentInitafter projected content is initialisedread @ContentChild
ngAfterViewInitafter the component’s view is initialisedread @ViewChild, focus, measure
ngOnDestroyjust before the component is destroyedunsubscribe, clear timers

Common mistakes with Lifecycle Hooks

  • Fetching data in the constructor, which runs before inputs are available.
  • Forgetting ngOnDestroy and leaking subscriptions each time the component is recreated.

Angular Lifecycle Hooks— Interview Questions & FAQs

What is the difference between the constructor and ngOnInit?+

The constructor runs when the class is instantiated, before Angular sets any @Input. ngOnInit runs after the first change detection pass, so inputs are populated — which is why data fetching belongs there.

Related Angular Topics

Keep learning with these closely related lessons.

Ready to use your Angular skills?

Find verified Angular internships and fresher developer jobs across India.

Browse Angular Internships