0
0
Angularframework~5 mins

Why lifecycle hooks matter in Angular

Choose your learning style9 modes available
Introduction

Lifecycle hooks help you run code at important moments in a component's life, like when it starts or stops. This keeps your app organized and working smoothly.

You want to fetch data right after a component appears on the screen.
You need to clean up resources like timers or subscriptions when a component is removed.
You want to react when input data to a component changes.
You want to run code after the component's view is fully loaded.
You want to detect and respond to changes in component properties.
Syntax
Angular
import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-example',
  template: `<p>Example works!</p>`
})
export class ExampleComponent implements OnInit, OnDestroy {
  ngOnInit() {
    // Code to run when component starts
  }

  ngOnDestroy() {
    // Code to run when component is removed
  }
}

Lifecycle hooks are methods you add to your component class.

Angular calls these methods automatically at the right time.

Examples
This runs code when the component is created.
Angular
import { OnInit } from '@angular/core';

export class MyComponent implements OnInit {
  ngOnInit() {
    console.log('Component started');
  }
}
This runs code when the component is about to be destroyed.
Angular
import { OnDestroy } from '@angular/core';

export class MyComponent implements OnDestroy {
  ngOnDestroy() {
    console.log('Component removed');
  }
}
This runs when input properties change.
Angular
import { OnChanges, SimpleChanges } from '@angular/core';

export class MyComponent implements OnChanges {
  ngOnChanges(changes: SimpleChanges) {
    console.log('Input changed', changes);
  }
}
Sample Program

This component starts a timer when it appears and stops it when removed. This prevents the timer from running forever and wasting resources.

Angular
import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-timer',
  template: `<p>Seconds passed: {{seconds}}</p>`
})
export class TimerComponent implements OnInit, OnDestroy {
  seconds = 0;
  intervalId?: number;

  ngOnInit() {
    this.intervalId = window.setInterval(() => {
      this.seconds++;
    }, 1000);
  }

  ngOnDestroy() {
    if (this.intervalId !== undefined) {
      clearInterval(this.intervalId);
    }
  }
}
OutputSuccess
Important Notes

Always clean up in ngOnDestroy to avoid memory leaks.

ngOnInit is a good place to start fetching data or initializing values.

Use lifecycle hooks to keep your component's behavior clear and predictable.

Summary

Lifecycle hooks let you run code at key moments in a component's life.

They help manage resources and keep your app efficient.

Using them makes your components easier to understand and maintain.