angular
/

Angular Lifecycle Hooks – Managing Component Life

Last Sync: Today

On this page

4
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

angular

Angular Lifecycle Hooks – Managing Component Life

Understanding the Lifecycle

An Angular component has a lifecycle managed by the framework. From the moment it is instantiated to the moment it is destroyed, Angular provides 'hooks'—specific methods you can implement to tap into key moments. As a Technical Lead, mastering these hooks is essential for managing heavy resources like the Revochamp AI engine, ensuring you initialize data correctly and clean up memory to prevent leaks.

  1. Common Lifecycle Hooks

While there are many hooks, a few are used in almost every professional component. You implement these by adding the corresponding interface to your class and defining the method.

  • ngOnChanges(): Responds when Angular sets or resets data-bound input properties (@Input). It receives a SimpleChanges object.
  • ngOnInit(): Called once after the first ngOnChanges. This is the best place to fetch data from your Python APIs.
  • ngOnDestroy(): Called just before Angular destroys the component. Use this to unsubscribe from Observables and stop timers.

  1. Implementation Example

TypeScriptRead-only
1
import { Component, OnInit, OnDestroy, Input, SimpleChanges, OnChanges } from '@angular/core';
import { Subscription } from 'rxjs';

@Component({ ... })
export class ProjectEditorComponent implements OnInit, OnChanges, OnDestroy {
  @Input() projectId!: string;
  private sub!: Subscription;

  ngOnChanges(changes: SimpleChanges) {
    console.log('Project ID changed:', changes['projectId'].currentValue);
  }

  ngOnInit() {
    console.log('Component initialized. Fetching project data...');
    // this.sub = this.apiService.getData().subscribe();
  }

  ngOnDestroy() {
    console.log('Cleaning up resources...');
    if (this.sub) this.sub.unsubscribe();
  }
}

  1. View & Content Hooks

Sometimes you need to interact with the DOM or child components. Hooks like ngAfterViewInit are triggered only after Angular has fully initialized the component's views and child views.

HookTimingBest Use Case
ngOnChangesBefore ngOnInitReacting to @Input changes
ngOnInitAfter first OnChangesInitial API calls / logic setup
ngDoCheckEvery change detectionCustom change detection logic
ngAfterViewInitAfter view rendersAccessing @ViewChild elements
ngOnDestroyBefore destructionUnsubscribing / memory cleanup

Test Your Knowledge

Q1
of 3

Which lifecycle hook is called first when a component is initialized with inputs?

A
ngOnInit
B
ngOnChanges
C
ngAfterViewInit
D
ngDoCheck
Q2
of 3

Where is the best place to perform a cleanup, such as unsubscribing from an Observable?

A
ngOnInit
B
constructor
C
ngOnDestroy
D
ngAfterViewInit
Q3
of 3

True or False: ngOnInit is called every time a component's input changes.

A
True
B
False

Frequently Asked Questions

Why use ngOnInit instead of the Constructor?

The constructor is a TypeScript feature for class instantiation, but Angular hasn't finished setting up the component (like @Input properties) yet. ngOnInit is an Angular-specific hook that ensures all inputs and DI services are ready for use.

When should I use ngOnDestroy?

Every time you use a manual '.subscribe()' in your TypeScript, you should unsubscribe in ngOnDestroy. This prevents memory leaks, especially in single-page applications where components are frequently created and removed.

What is the SimpleChanges object?

In ngOnChanges, Angular passes a SimpleChanges object that contains the previous and current value of every changed @Input property. This allows you to compare values and trigger logic only when specific inputs change.

Previous

angular error handling

Next

angular view encapsulation

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.