Component Lifecycle Hooks

🅰️ Angular Lesson 6 Intermediate

Angular manages component lifecycles through built-in hooks, allowing you to run custom code when components are created, modified, or destroyed.

1 Core Hook Order

The most important lifecycle hooks are run in a specific sequence:

  • ngOnChanges: Runs when input properties (@Input) are first initialized or updated.
  • ngOnInit: Runs once after input properties are first set. This is the best place to fetch data from services.
  • ngAfterViewInit: Runs after the component's view templates are fully initialized. Useful for direct DOM queries.
  • ngOnDestroy: Runs just before the component is destroyed. Critical for cleanups (unsubscribing from Observables, clearing intervals).
2 Implementing Lifecycle Interfaces

To use these hooks, implement their respective TypeScript interfaces:

TypeScript — Component Lifecycle
import { Component, OnInit, OnDestroy, Input, SimpleChanges, OnChanges } from '@angular/core';

@Component({
  selector: 'app-tracker',
  template: `

Tracking data updates...

` }) export class TrackerComponent implements OnChanges, OnInit, OnDestroy { @Input() dataId: number = 0; ngOnChanges(changes: SimpleChanges) { if (changes['dataId']) { console.log('dataId updated:', changes['dataId'].currentValue); } } ngOnInit() { console.log('Component initialized — fetch startup data here.'); } ngOnDestroy() { console.log('Component destroyed — clear active listeners.'); } }
3 Code Challenge
Challenge: Write a component that starts a timer inside ngOnInit using setInterval. Ensure the timer is properly cleared in ngOnDestroy to prevent memory leaks.