简体   繁体   English

角度:破坏动态组件

[英]Angular: destroy dynamic component

Working on a chat application, I am using this to create multiple ChatComponent (as dynamic components). 在一个聊天应用程序上,我正在使用它来创建多个ChatComponent(作为动态组件)。

loader.service.ts

import { ChatComponent } from '../components/shared/chat/chat.component';

@Injectable()
export class LoaderService {

    constructor( @Inject(ComponentFactoryResolver) factoryResolver ) 
    { 
      this.factoryResolver = factoryResolver
    }

    setRootViewContainerRef(viewContainerRef){
      this.rootViewContainer = viewContainerRef
    }

    addDynamicComponent(timeIdentifier){
      const factory = this.factoryResolver.resolveComponentFactory(ChatComponent);      
      const component = factory.create(this.rootViewContainer.parentInjector)
      component.instance.timeIdentifier = timeIdentifier;
      this.rootViewContainer.insert(component.hostView)
    }
  }

chat-container.component.ts

export class ChatContainerComponent implements OnInit {

    @ViewChild('chat', { read: ViewContainerRef }) viewContainerRef: ViewContainerRef

    constructor( protected loaderService: LoaderService, protected route: ActivatedRoute ) { }

    ngOnInit() {

        this.route.params.subscribe(params => {
            this.loaderService.setRootViewContainerRef(this.viewContainerRef)
            this.loaderService.addDynamicComponent(params['timeIdentifier'])
        });
    }
}

This way I can generate multiple "ChatComponent" as dynamic components. 这样,我可以生成多个“ ChatComponent”作为动态组件。

But how can I destroy them once they are created ? 但是一旦创建它们,我如何销毁它们呢?


EDIT 编辑


I have added this in ChatComponent (which have been created by the component factory) 我已经在ChatComponent中添加了此内容(由组件工厂创建)

this.cmpRef.destroy();

But when i call this, i got stuck in infinite loop with errors like so: 但是当我打电话给我时,我陷入了无限循环,出现了如下错误:

ERROR RangeError: Maximum call stack size exceeded

The created components from the factory are of type ComponentRef . 从工厂创建的组件的类型为ComponentRef This class has the destroy function to destroy the instance and the associated structures. 此类具有destroy功能,可以销毁实例和关联的结构。

Check it here: https://angular.io/api/core/ComponentRef 在此处检查: https : //angular.io/api/core/ComponentRef

I found a better way to destroy a component, you can do: 我找到了销毁组件的更好方法,您可以执行以下操作:

addDynamicComponent(timeIdentifier){
  const factory = this.factoryResolver.resolveComponentFactory(ChatComponent);      
  const component = factory.create(this.rootViewContainer.parentInjector)
  component.instance.timeIdentifier = timeIdentifier;
  component.instance.autodestroy = () => component.destroy();
  this.rootViewContainer.insert(component.hostView)
}

And inside your component class you create a method autodestroy and call it when you want destroy it. 在组件类中,您将创建一个方法autodestroy ,并在您想要销毁它时调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM