Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Angular component variables be set to null in ngOnDestroy()?

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;
  }

}
like image 757
Kumanan Avatar asked Apr 12 '18 18:04

Kumanan


People also ask

What is ngOnDestroy ()?

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.

What is the use of ngOnDestroy in angular?

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.

Can we use ngOnDestroy in service?

As it turns out, ngOnDestroy works not only on Component or Directive, it is also usable for Service and Pipe.

Why ngOnDestroy is not getting called?

ngOnDestroy doesn't get called because some components do not get destroyed when navigating to a different route.


1 Answers

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

like image 83
Suren Srapyan Avatar answered Oct 05 '22 08:10

Suren Srapyan