在onDestroy之前的Angular2分离视图?

前端之家收集整理的这篇文章主要介绍了在onDestroy之前的Angular2分离视图?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在组件已被销毁之前,Angular2中是否有可能获得通知!?即什么时候要被销毁.

我有一个容器组件,它的一个子容器上有一个ViewContainerRef,用于动态加载视图.如果容器组件本身被破坏(在我的情况下由于父组件中的* ngFor指令),我想分离当前在ViewContainerRef中加载的视图并再次将它附加到另一个容器上.

事情是:在ngOnDestroy()生命周期钩子中,ViewContainerRef已被清除,因此所有视图都被销毁,不再分离.

解决方法

我现在的解决方案(不是真正的解决方法)是实现使用ngFor指令的父组件的ngOnChanges().如果由ngFor迭代阵列已经改变并且其长度比以前我简单地分离所有容器(@ViewChildren容器:QueryList)的观点更短,并将它们映射到所述容器(图).
然后,我通过迭代新容器列表并从containers中加载ViewRef,在containers.changed侦听器中再次重新插入映射视图.

@Component({
 selector: 'container-collection',directives: [Container],template: `<container *ngFor="let i of views"></container>`
})
export class ContainerCollection {
 public views = [];

 @ViewChildren(Container) private containers: QueryList<Container>;

 private viewMap = new Map<Container,ViewRef>();

 public ngOnChanges(changes: {[key: string]: SimpleChange]}): void {
  if(changes['views']) {
   //detach all views and remember which container had which view
   this.viewMap = new Map<Container,ViewRef>();

   this.containers.forEach(container => {
    var view = container.viewContainer.detach();
    if(view)
     this.viewMap.set(container,view);
   });
  }
 }

 public ngAfterViewInit(): void {
  //insert the views again (into the appropriate containers)
  this.containers.changes.subscribe( () => {
   this.containers.forEach(container => {
    var view = this.viewMap.get(container);
    if(view)
     container.viewContainer.insert(view);
   });
  });
 }
}

@Component({
 selector: 'container',template: `<div #viewContainer></div>`
})
export class Container {
 @ViewChild('viewContainer') public viewContainer;
}

代码只是草稿,可能包含语法错误.但这个想法(对我有用)应该是清楚的.

Angular2团队会很好地添加一个LifeCycle钩子,它会被一个组件实际销毁之前调用. (例如ngBeforeDestroy())左右.

猜你在找的Angularjs相关文章