Angular - ComponentsHow can you ensure cleanup of a subscription created in ngOnInit to avoid memory leaks in Angular?ANo need to unsubscribe if using ngOnInitBUnsubscribe inside ngOnInit lifecycle hookCUnsubscribe inside constructorDUnsubscribe inside ngOnDestroy lifecycle hookCheck Answer
Step-by-Step SolutionSolution:Step 1: Identify when to clean subscriptionsSubscriptions should be cleaned when the component is destroyed to avoid leaks.Step 2: Use ngOnDestroy for cleanupngOnDestroy is the lifecycle hook designed for cleanup tasks like unsubscribing.Final Answer:Unsubscribe inside ngOnDestroy lifecycle hook -> Option DQuick Check:Cleanup subscriptions in ngOnDestroy [OK]Quick Trick: Unsubscribe in ngOnDestroy to prevent leaks [OK]Common Mistakes:Unsubscribing too earlyIgnoring unsubscribeTrying to unsubscribe in constructor
Master "Components" in Angular9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallPerf
More Angular Quizzes Angular Modules - Shared modules for reusable components - Quiz 8hard Angular Modules - Module lazy loading preview - Quiz 10hard Angular Modules - Module lazy loading preview - Quiz 6medium Component Interaction - @ContentChild and content projection - Quiz 3easy Component Interaction - Template reference for direct access - Quiz 3easy Directives - *ngSwitch for multiple conditions - Quiz 13medium Directives - ngClass for dynamic classes - Quiz 6medium Lifecycle Hooks - ngOnDestroy for cleanup - Quiz 5medium Pipes - Creating custom pipes - Quiz 7medium Templates and Data Binding - Template reference variables - Quiz 7medium