angular 2 何时在组件上调用 onDestroy?

ANe*_*own 4 javascript angular

我无法弄清楚 angular 何时决定调用onDestory事件?

当我使用*ngIF指令切换组件时,不会调用 onDestory 并且组件的状态被维护,就好像它使用组件的相同实例一样?

任何人都可以详细说明 angular(2) 何时破坏组件?以及如何在切换时实现更新的组件实例*ngIf

Max*_*kyi 12

Angular 中的大多数 DOM 操作都是使用ViewContainerRef执行的。特别是,此机制由以下人员在内部使用ngIf

private _updateView() {
    ...
    this._viewContainer.clear();
    ...
      this._thenViewRef =
          this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context);
    }
  }
Run Code Online (Sandbox Code Playgroud)

路由器插座

@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);
    }
Run Code Online (Sandbox Code Playgroud)

每当调用viewContainer.clear()viewContainer.remove(index)方法时,相关组件或嵌入视图(使用ng-template)被删除并ngOnDestroy在它们上调用生命周期钩子。

任何人都可以详细说明 angular(2) 何时破坏组件?

当使用ngIf和这样的结构指令ngFor时,当路由器导航离开当前router-outlet指令时,或者当您手动删除动态组件或使用viewContainerRef.

您可以使用以下内容阅读有关 DOM 操作的更多信息ViewContainerRef

  • 我有点惊讶你的回答得到的赞成票这么少,这对于角度来说是如此重要 (3认同)