How to destroy all components created using DynamicComponentLoader in angular2?

Hi ... I found a message about adding and removing components using Dynamic Component Loader and Dispose Method. I want to destroy components created immediately. I have a demo plunker and a source where I found the Angular 2 demo - Add / Remove components on the fly ... I know that I want to save everything componentrefin an array, and then repeat them and destroy ... But I can not get it to work ... Please help me how to destroy all components.

     remove() {
    this._ref.dispose();
  }

this is how i destroy one component ... how to destroy everything at once?

+4
source share
1 answer

, , , - ComponentRef dispose() , . .

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
  }
}

- , dispose() , "", DynamicComponent , , .

, , , , , ...

: , , , , DynamicComponentLoader, .

, , DCL, ( ) , , , , .

- . :

@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 = [];
  }

}
+6

Source: https://habr.com/ru/post/1622683/


All Articles