简体   繁体   中英

Angular: destroy dynamic component

Working on a chat application, I am using this to create multiple ChatComponent (as dynamic components).

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.

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)

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 . This class has the destroy function to destroy the instance and the associated structures.

Check it here: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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