Lifecycle events

💡 The most important ones are:

  1. ngOnInit
  2. 🚪 ngOnChanges
  3. ⚰️ ngOnDestroy

All events:

@Component({ selector: 'app-sample', template: `...` })
class Sample implements OnInit, OnChanges, OnDestroy {
  ngOnInit(): void {}
  ngOnChanges(changes: SimpleChanges): void {}
  ngOnDestroy(): void {}
}

Unsubscribing on destroy

Popular ways of unsubscribing onDestroy

  1. some people created a destroyed = new Subject() helper (then used takeUntil and this.destroyed.next())
  2. @UntilDestroy is a popular way of doing unsubscribes (using decorators)
  3. since A16 we have a builtin takeUntilDestroy
    • this can only be used in injection contexts (constructor or "pre" constructor)
    • use .pipe(takeUntilDestroyed()).subscribe(...)
    • it uses DestroyRef under the hood, which is needed if you're not inside an injection context:
      • injection: destroyRef = inject(DestroyRef)
      • usage: .pipe(takeUntilDestroyed(this.destroyRef)).subscribe(...)