1

I am adding child components through a button in the parent component dynamically. It works fine and I can add as many child as I want but as soon as I delete the last child (just added) , adding a new child doesn't work anymore.

Here is how I am doing it:

parent.ts

import {Component,DynamicComponentLoader,ElementRef,AfterViewInit,Injector} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {ChildComponent} from './child.ts';


@Component({
    selector: 'app',
    host: {'id':'children'},
    template: `<button (click)="addChild()" >Add Child</button><div #here></div>`
})
class AppComponent implements AfterViewInit{
    public counter = 0;
    constructor(private _loader:DynamicComponentLoader,private _elementRef:ElementRef) {}
    addChild(){
        var app = this;
        this._loader.loadIntoLocation(ChildComponent,this._elementRef,'here').then(child => {
            child.instance.id = app.counter++;
        });
    }

}

bootstrap(AppComponent);

child.ts

import {Component,OnInit} from 'angular2/core';

@Component({
    selector: "div",
    host: {'[attr.id]':'id'},
    template: "Child Component <button (click)='remove()' >Remove Me</button>"
})
export class ChildComponent implements OnInit{
    public id:number;

    remove(){
        $("#"+this.id).remove();
    }
};
Eesa
  • 2,762
  • 2
  • 32
  • 51
  • Can you preproduce it on plnkr? https://angular.io/resources/live-examples/quickstart/ts/plnkr.html – martin Mar 02 '16 at 12:43

2 Answers2

0

update

.dispose() is destroy() since beta.16

original

I think you should use

child.dispose();

instead of removing the tags using jQuery.

See also Angular 2 - Adding / Removing components on the fly

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

You could use the dispose method on the ComponentRef class to remove your component.

For this, you need to provide it to the component instance itself this way:

addChild(){
    var app = this;
    this._loader.loadIntoLocation(ChildComponent,this._elementRef,'here').then(child => {
        child.instance.id = app.counter++;
        child.instance.ref = child;
    });
}

And use it like that in your component:

@Component({
  selector: "div",
  host: {'[attr.id]':'id'},
  template: "Child Component <button (click)='remove()' >Remove Me</button>"
})
export class ChildComponent implements OnInit{
  public id:number;

  remove(){
    this.ref.dispose();
  }
};
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360