0
0
Angularframework~5 mins

ngOnDestroy for cleanup in Angular - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the ngOnDestroy lifecycle hook in Angular?
The ngOnDestroy hook is used to perform cleanup just before Angular destroys a component or directive. It helps free resources like subscriptions or timers to prevent memory leaks.
Click to reveal answer
beginner
When exactly is ngOnDestroy called in an Angular component?
ngOnDestroy is called right before Angular removes the component or directive from the DOM, such as when navigating away or conditionally hiding the component.
Click to reveal answer
intermediate
Why should you unsubscribe from Observables inside ngOnDestroy?
Unsubscribing inside ngOnDestroy stops ongoing Observable streams to avoid memory leaks and unexpected behavior after the component is gone.
Click to reveal answer
intermediate
Show a simple example of using ngOnDestroy to clear a timer.
Inside ngOnDestroy, call clearInterval or clearTimeout to stop timers started in the component, preventing them from running after destruction.
Click to reveal answer
beginner
What happens if you forget to implement cleanup in ngOnDestroy?
If cleanup is missed, resources like subscriptions or timers keep running, causing memory leaks and bugs because the component is no longer active but still consuming resources.
Click to reveal answer
What is the main use of ngOnDestroy in Angular?
ATo handle user input events
BTo initialize component data
CTo render the component template
DTo clean up resources before component destruction
When should you unsubscribe from Observables in Angular?
AInside <code>ngOnDestroy</code>
BInside <code>ngOnInit</code>
CInside the constructor
DNever unsubscribe
Which Angular lifecycle hook is called just before a component is removed from the DOM?
AngOnDestroy
BngAfterViewInit
CngOnChanges
DngDoCheck
What could happen if you forget to clear timers in ngOnDestroy?
ATimers stop automatically
BTimers keep running causing unexpected behavior
CAngular throws an error
DNothing happens
Which of these is NOT a reason to use ngOnDestroy?
ATo unsubscribe from Observables
BTo clear intervals or timeouts
CTo fetch data from a server
DTo release resources
Explain why and how you use ngOnDestroy in an Angular component.
Think about what happens when a component is removed and what resources might still be running.
You got /4 concepts.
    Describe a real-life example where forgetting to implement ngOnDestroy cleanup could cause problems.
    Imagine a component that keeps listening to data even after you leave its page.
    You got /3 concepts.