Angular Lifecycle Hooks (ngOnInit, ngOnDestroy, and More)
Learn the lifecycle hooks that control setup, updates, and cleanup in Angular components.
Lifecycle hooks are methods Angular calls at different stages of a component’s life. ## The ones you will use most ### ngOnInit Runs once after the component is created. Good for: - loading initial data - starting subscriptions ### ngOnDestroy Runs once before the component is removed. Good for: - cleaning subscriptions - stopping timers ## Example ```ts import { Component, OnDestroy, OnInit } from '@angular/core'; import { Subscription, interval } from 'rxjs'; @Component({ selector: 'app-timer', standalone: true, template: `<p>Seconds: {{ seconds }}</p>`, }) export class TimerComponent implements OnInit, OnDestroy { seconds = 0; private sub?: Subscription; ngOnInit() { this.sub = interval(1000).subscribe(() => this.seconds++); } ngOnDestroy() { this.sub?.unsubscribe(); } } ``` ## Quick tip - HTTP Observables complete automatically, usually safe. - Streams like `interval`, router events, websockets need cleanup. > Next: Template-driven forms, building real input screens.