The Angular documentation says
ngOnDestroy(): Cleanup just before Angular destroys the directive/component. Unsubscribe Observables and detach event handlers to avoid memory leaks. Called just before Angular destroys the directive/component.
Some developers are saying that the component properties (class variables) should also be set to null to avoid memory leaks. Is this true?
export class TestComponent implements OnInit, OnDestroy {
public name: string;
constructor() { }
ngOnInit() {
this.name = 'John';
}
ngOnDestroy() {
// is this code really necessary.
this.name = null;
}
}
ngOnDestroy() gets called when a component is about to be destroyed. Notice how the example "destroys" the child component via the conditional ngIf='showChild'. By toggling the value of showChild, Angular creates and destroys the child component each time this value changes.
NgOnDestroy is a lifecycle method that can be added by implementing OnDestroy on the class and adding a new class method named ngOnDestroy . It's primary purpose according to the Angular Docs is to “Cleanup just before Angular destroys the directive/component.
As it turns out, ngOnDestroy works not only on Component or Directive, it is also usable for Service and Pipe.
ngOnDestroy doesn't get called because some components do not get destroyed when navigating to a different route.
No you don't need that. Component just is a class and when it is shown, an instance is created. When the component is destroyed, the associated object is left without reference and as soon as possible it will be garbage collected.
As documentation says, you need only to use in those cases with Observables and event handlers as they will not be removed with garbage collector if they are in the active state.
Unsubscribe Observables and detach event handlers to avoid memory leaks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With