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

2

8

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

}
Foreshadow answered 12/4, 2018 at 18:11 Comment(0)
G
10

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

Govea answered 12/4, 2018 at 18:13 Comment(2)
I implemented a tree and I have a node component that renders the node with virtual scroll. I have an input in the node component @Input() nodeChanged: Subject<void>; and the following code ngOnInit() { this.nodeChanged$ = this.nodeChanged.subscribe(() => ... ) }. In this case I had to set this.nodeChanged to null in ngOnDestroy like so ngOnDestroy() { this.nodeChanged = null; this.nodeChanged.unsubscribe();} to avoid the ObjectUnsubscribedErrorTerrieterrier
This happened because angular passed in 2 nodes the same reference of the subject. So, on the second node I was subscribing to a subject that was already unsubscribedTerrieterrier
O
0

Yes, you need to do that. I faced the same problem when I was storing the data in a variable and calling ngOnDestroy while switching between different child component.

The component in the hope that it will get automictically removed but it didn't, the data was not getting removed from that variable so setting it to null in ngOnDestroy helped me.

ngOnDestroy(){  this.home=null;}
Obadiah answered 20/10, 2022 at 7:19 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Persas

© 2022 - 2024 — McMap. All rights reserved.