Use Lifecycle Hooks Carefully
Run setup and cleanup work at the correct component stage.
Lesson content
Description Angular calls lifecycle hooks while creating, checking, and destroying a component. Use ngOnInit for initialization that depends on inputs and ngOnDestroy for manual cleanup. Avoid changing template state during checking hooks. Code export class Clock implements OnInit, OnDestroy { timer?: number; ngOnInit() { this.timer = window.setInterval(() => this.tick(), 1000); } ngOnDestroy() { window.clearInterval(this.timer); } tick() { /* update state */ } } Note The exact APIs can vary by Angular releases. Keep the stable concept separate from API-specific changes. Tip Build the smallest working use lifecycle hooks carefully example first, then add production concerns such as errors, cleanup, typing, and tests. Key takeaway Prefer framework-managed cleanup such as the async pipe or takeUntilDestroyed when possible.