Using ngOnDestroy for Cleanup in Angular
📖 Scenario: You are building a simple Angular component that starts a timer when it loads. To keep your app clean and avoid memory leaks, you need to stop the timer when the component is destroyed.
🎯 Goal: Create an Angular standalone component that starts a timer counting seconds on load and properly cleans up the timer using ngOnDestroy when the component is removed.
📋 What You'll Learn
Create a standalone Angular component named
TimerComponentAdd a variable
seconds initialized to 0Start a timer using
setInterval that increments seconds every secondStore the timer ID in a variable called
timerIdImplement the
ngOnDestroy lifecycle method to clear the timer using clearInterval(timerId)💡 Why This Matters
🌍 Real World
Timers are common in apps for clocks, countdowns, or refreshing data. Cleaning up timers prevents app slowdowns and bugs.
💼 Career
Understanding Angular lifecycle hooks like ngOnDestroy is essential for building efficient, bug-free Angular applications.
Progress0 / 4 steps