Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does angular 2 call onDestroy on a component?

I am not able to figure out when does the angular decide to call onDestory event?

When I toggle the component with *ngIF directive, onDestory is not called and the state of the component is maintained as if it is using the same instance of the component?

Can anybody elaborate as to when angular(2) destroys component? And how to achieve newer instance of component when toggling with *ngIf?

like image 535
ANewGuyInTown Avatar asked Dec 13 '22 19:12

ANewGuyInTown


1 Answers

Most DOM manipulations in Angular are performed using ViewContainerRef. In particular, this mechanism is used internally by ngIf:

private _updateView() {
    ...
    this._viewContainer.clear();
    ...
      this._thenViewRef =
          this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context);
    }
  }

and router-outlet:

@Directive({selector: 'router-outlet', exportAs: 'outlet'})
export class RouterOutlet implements OnDestroy, OnInit {
    constructor(..., private location: ViewContainerRef, ...)
    detach(): ComponentRef<any> {
        ...
        this.location.detach();
        ...
    }
    attach(ref: ComponentRef<any>, activatedRoute: ActivatedRoute) {
        ...
        this.location.insert(ref.hostView);
    }

Whenever either viewContainer.clear() or viewContainer.remove(index) method is called the relevant components or embedded views (created with ng-template) are removed and ngOnDestroy lifecycle hook is called on them.

Can anybody elaborate as to when angular(2) destroys component?

This will happen when using structural directives like ngIf and ngFor, when router navigates away from current router-outlet directive or when you manually remove dynamic components or embedded views using viewContainerRef.

You can read more about DOM manipulation using ViewContainerRef in:

  • Exploring Angular DOM manipulation techniques using ViewContainerRef
like image 120
Max Koretskyi Avatar answered Dec 16 '22 10:12

Max Koretskyi