I've seen a lot of question related to ngOnDestroy. I think many of us not using it correctly or not using it at all.
I just want to see a list of tips how can you properly use ngOnDestroy and what should we do in the best scenario to prevent memory leaks, speed up and optimize web apps.
What do you must to do in every case when you use it?(What are the steps you MUST to take?)
How far you need to go if you want to do it perfectly? Nullifying all references etc.
How to use OnDestroy properly
8.6k views Asked by Jánosi-Borsos Róbert At
2
There are 2 answers
1
Sneha Pawar
On
The ngDestroy is called in a component’s lifecycle just before the instance of the component is finally destroyed. It is the perfect place to clean the component
import {OnDestroy } from '@angular/core'; // import from core
@Directive({
selector: '[destroyDirective]'
})
export class OnDestroyDirective implements OnDestroy { // implements OnDestroy
//Call Constructor and set hello Msg.
constructor() {
this.helloMsg = window.setInterval(() => alert('Hello, I am Anil'), 2000);
}
//Destroy to the component
ngOnDestroy() {
window.clearInterval(this.helloMsg);
}
}
Related Questions in ANGULAR
- Firebase link existing user to anonymous account?
- It doesnt always show all the books on my homepage
- Google adsense ads.txt status cannot be not found
- When I navigate to the URL'http://localhost:4200/', it redirects me back
- Ionic Angular Standalone ion-icon are not showing at all
- How to make Angular understand that view child is of a specific type, not a general ElementRef?
- vscode, debug angular, first time, doesn't debug, 2nd time stops at main.js then it's ok
- How to perform CRUD operations on a static JSON array in Angular? (without API)
- Ngrx props<>() method in createAction()
- How to animate rotation of an image inside input control?
- Detecting click inside and outside of the listening component in Angular
- Angular - type guard not narrowing types
- In node_modules file i am getting Angular genric error while using fontawesome in angular12
- Angular 16 sending null values to API
- GoogleCloud Error: Not Found The requested URL was not found on this server
Related Questions in OPTIMIZATION
- Optimize LCP ReactJs
- Efficiently processing many small elements of a collection concurrently in Java
- How to convert the size of the HTML document from 68 Kb to the average of 33 Kb?
- Optimizing Memory-Bound Loop with Indirect Prefetching
- Google or-tools soft constraint issue
- How to find function G(x), and make for every x, G(x) always returns fixed point for another function F(G(x))
- Trying to sort a set of words with the information theory to solve Worlde in Python but my program is way to slow
- Do conditional checks cause bottlenecks in Javascript?
- Hourly and annual optimization problem over matrix
- Sending asynchronous requests without a pre-defined task list
- DBT - Using SELECT * in the staging layer
- Using `static` on a AVX2 counter function increases performance ~10x in MT environment without any change in Compiler optimizations
- Is this a GCC optimiser bug or a feature?
- Performance difference between two JavaScript code snippets for comparing arrays of strings
- Distribute a list of positive numbers into a desired number of sets, aiming to have sums as close as possible between them
Related Questions in MEMORY-LEAKS
- Would event listeners prevent garbage collecting objects referenced in outer function scopes?
- Top output says my app uses 33 gigs of memory but how?
- My React Nextjs web app is using up 100% of my ram and crashing when i try to do changes. Does anyone know how to fix this or what may be the cause?
- Trigger Warning: Mysterious Memory Spike on Google Drive Upload using Google Cloud Run
- Do I need to clear the cache manually when using PredicateSpec.readBody in order to avoid memory leaks?
- Interpreting Chrome memory tool's results for a memory leak?
- Why does setting flags on an NDArray view result in allocations? Are they guaranteed to be bounded?
- How to dispose delegate in blazor or c#
- Comment optimiser l'utilisation des resources mémoires (RAM) sur flutter?
- Chained calls may cause memory leaks?
- Unable to fix generator memory leak despite knowing where it's coming from
- Jest is taking a lot of heap memory with (strings)
- Cause of this SwiftData memory leak?
- AES-CTR PRNG Implementation in OpenSSL with Consistent Output and Memory Leak Issues
- Getting an error when triying to read a file: zsh: trace trap
Related Questions in ONDESTROY
- How to do some async cleanup work on app closure in Android .NET MAUI?
- How to set AdListener to null
- How to detect the exact moment when the app is killed?
- WallpaperManager does not work correctly on Android 12
- How to kill previous service before start new service in Java?
- Android Dialog throwing not attached to window manager
- In android lifecycle, is there any unique method gets called when app is swiped from recent app list?
- Save ExoPlayer position to continue playback after closing the view (onDestroy())
- Angular Interceptor and dialogs
- how do I save score in onDestroy() android studio?
- Get 'OnDestroy' overrides nothing error when trying to shutdown textToSpeech - Kotlin
- Is onDestroy() also indicate to the Garbage collector that the Activity object should be collected?
- onDestroy or dispose in flutter
- "this" is undefined in ngOnDestroy
- Why Svelte's onDestroy event is not executing URL.revokeObjectURL()?
Related Questions in LIFECYCLE-HOOK
- Uncaught SyntaxError: ambiguous indirect export: created in vue 3 life cycle hook
- When I refresh a page in Vue 3 , request is called but the component is not loaded
- Problem with AWS autoscaling lifecycle hook integrated with lambda (python) and jenkins
- Cannot scrollIntoView in vue onMounted hook
- Behavior of the custom-element-upgrade process when the constructor throws an exception - lifecycle callbacks don't fire
- Do we need afterViewInit lifecycle hook anymore in angular?
- vue created doesn´t fire when a new element is inserted
- How can I remove manually added event listeners on beforeDestory hook of one component before redirecting to any another component, in Vuejs2?
- Vue lifecycle hook race condition
- AWS Autoscaling delay launch and terminate
- nativescript-vue cannot read data property in lifecycle hooks
- Why get undefined after the render of the DOM in the following case?
- Laravel test lifecycle hook
- Running scripts using lifecycle hook does not work properly in kubernetes
- Why is this.value undefined/null on every lifecycle hook when using [ngModel]="true"
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Popular Tags
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
One scenario where you are using Observable and subscribing it in a component and are getting a stream of data i.e Firebase. You should use ngOnDestroy and unsubscribe it when you leave the page to prevent the memory leak.