7

I went through angular dynamically loading components. But i could not find how to remove the component dynamically.

My requirement is that the chat application loads dynamic component(image/graph/list/table) as per the conversation. But how can i destroy the component if the conversation moves forward.

I am trying to destroy dynamic component with external event.

Please help how to proceed.

EDIT: https://stackblitz.com/angular/emjkxxxdxmk?file=src%2Fapp%2Fad-banner.component.ts

I developed my code according to this example. Instead of time interval, I need to use a API call from a service that is subscribed another component(chat component).

Below API response can load the component.I am looking for how to destroy the already loaded component i use the API call again.

public sendMessage(data): void {
    this.messages.push(this.message);
    this.API.getResponse(data).subscribe(res => {
      this.previousContext = res.context;
      console.log('res', res);
      if (res.result.type == 'table') {
        this.DataService.setTrigger(new AdItem(Table2Component, res));
      }
      this.messages.push(
        new Message(res.text, 'assets/images/bot.png', new Date(), 'chatbot')
      );
    });
    this.message = new Message('', 'assets/images/user.png', this.message.timestamp, 'user');
  }
1
  • Please provide some code so we can retrace your steps. Commented Sep 16, 2018 at 12:54

1 Answer 1

12

Use destroy() method

Destroys the component instance and all of the data structures associated with it.

ref:ComponentRef<any>;
loadComponent() {
    this.currentAdIndex = (this.currentAdIndex + 1) % this.ads.length;
    let adItem = this.ads[this.currentAdIndex];

    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);

    let viewContainerRef = this.adHost.viewContainerRef;
    viewContainerRef.clear();

    let componentRef = viewContainerRef.createComponent(componentFactory);
    this.ref=componentRef;
    (<AdComponent>componentRef.instance).data = adItem.data;

  }

  removeComponent(){
   try{
       this.ref.destroy();
   }
   catch(e){
   }
  }

Example:https://stackblitz.com/edit/destroy?file=src/app/ad-banner.component.ts

Sign up to request clarification or add additional context in comments.

4 Comments

when do i call this method? It works only if the component exits. If the component doesn't exits ref.destroy() is showing error. I tried with the below code.. but it didn't work. if(this.ref!=null){this.ref.destroy();}
why do you want to destroy if there is no component
If there is no component.. it should not execute that line.. i am unable toput the if condition there. this.ref shows undefined when I console.log(). Please help on the if condition.., it shows undefined..
instead of if use try catch

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.