2016-03-02 33 views
1

我通過父組件中的按鈕動態添加子組件。它工作正常,我可以添加儘可能多的孩子,但只要我刪除最後一個孩子(剛剛添加),添加一個新孩子不再工作。Angular2 - 刪除所有/最近的子組件後無法添加子組件

下面是我這樣做:

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(); 
    } 
}; 
+0

你能preproduce它plnkr? https://angular.io/resources/live-examples/quickstart/ts/plnkr.html – martin

回答

0

見你可以使用在ComponentRefdispose方法來刪除您的組件。

對於這一點,你需要把它提供給組件實例本身是這樣的:

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

而且使用它一樣,在您的組件:

@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(); 
    } 
};