# ngOnInit, ngOnDestroy & ngOnChanges — Angular

Source: https://www.geekswithgeeks.com/en/angular/ng-lifecycle-hooks

> Hook into key moments of a component's life.

## Why hooks exist

Angular calls specific methods at specific moments — creation, updates, destruction — if your class implements them. This is how you run setup and cleanup code at the right time.

## ngOnInit & ngOnDestroy

`ngOnInit` runs once after the component's inputs are first set — the usual place to fetch initial data. `ngOnDestroy` runs right before the component is removed — clean up subscriptions and timers there.

```typescript
export class TimerComponent implements OnInit, OnDestroy {
  private intervalId?: ReturnType<typeof setInterval>;

  ngOnInit() {
    this.intervalId = setInterval(() => this.tick(), 1000);
  }

  ngOnDestroy() {
    clearInterval(this.intervalId);
  }

  tick() { /* ... */ }
}
```

## ngOnChanges

`ngOnChanges` fires whenever a bound `@Input()` value changes, receiving both the previous and current values.

```typescript
ngOnChanges(changes: SimpleChanges) {
  if (changes['rating']) {
    console.log(changes['rating'].previousValue, changes['rating'].currentValue);
  }
}
```

**Quiz:** Where should you clear a timer or unsubscribe from a stream?

- [ ] ngOnInit
- [ ] ngOnChanges
- [x] ngOnDestroy

*Answer:* ngOnDestroy. ngOnDestroy runs right before the component is removed — the correct place for cleanup.
