8
votes

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

}
1

1 Answers

10
votes

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