我通過父組件中的按鈕動態添加子組件。它工作正常,我可以添加儘可能多的孩子,但只要我刪除最後一個孩子(剛剛添加),添加一個新孩子不再工作。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();
}
};
你能preproduce它plnkr? https://angular.io/resources/live-examples/quickstart/ts/plnkr.html – martin