我通过父组件中的按钮动态添加子组件。它工作正常,我可以添加尽可能多的孩子,但只要我删除最后一个孩子(刚刚添加),添加一个新孩子不再工作。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