How to destroy all the Components created using DynamicComponentLoader in angular2?

后端 未结 1 1975
故里飘歌
故里飘歌 2021-01-13 03:57

Hie...I found a post regarding Adding and removing of components using Dynamic Component Loader and Dispose Method. I want to destroy the components created all at once. I h

相关标签:
1条回答
  • 2021-01-13 04:44

    The simplest way to do what you're asking how to do is to keep track of the ComponentRefs as you add them and call dispose() on each in a loop when you want to remove them. See updated plunk

    export class App {
      ...
      private _children:ComponentRef[] = [];
    
      add() {
        this._dcl.loadIntoLocation(DynamicCmp, this._e, 'location').then((ref) => {
          ...
          this._children.push(ref);
        });
      }
    
      removeall(){
        this._children.forEach(cmp=>cmp.dispose());
        this._children = []; // not even necessary to get the components off the screen
      }
    }
    

    If for some reason it's super important that you only call dispose() once, you could create a "container", add your DynamicComponents as children of that, and then dispose the container, automatically disposing its children.

    Having said that, I can't imagine a situation where I'd prefer doing that over adding the four lines of code it takes to implement what I outlined above...

    Having said all that: If there's a way to use data binding to do what you're trying to do, you should favor that over falling back on DynamicComponentLoader unless you have a damn good reason not to.

    I'll be the first to tell you there are use-cases where DCL is needed, but in my (albeit brief) experience, for every five I initially thought needed it, I came up with data-binding solutions for at least three after giving it a little thought.

    In this case, doing that was trivial - see other updated plunk:

    @Component({
      selector: 'my-app',
      template : `
        <button (click)="add()">Add new component</button>
        <button (click)="removeAll()">Remove All</button>
        <template ngFor #child [ngForOf]="children">
           <div [dynamicCmp]="child"></div>
        </template>
      `,
      directives:[DynamicCmp]
    })
    export class App {
      children:number[] = [];
    
      add() {
        this.children.push(this.children.length+1);
      }
    
      removeAll(){
        this.children = [];
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题