Angular2 - 删除所有/最近的子组件后无法添加子组件

Angular2 - Can't add child component after deleting all/recent child components

本文关键字:组件 添加 最近 删除 Angular2      更新时间:2023-09-26

我正在通过父组件中的按钮动态添加子组件。它工作正常,我可以根据需要添加任意数量的孩子,但是一旦我删除最后一个孩子(刚刚添加),添加新的孩子就不再有效了。

这是我的做法:

父.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);

儿童网

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

更新

.dispose()beta.16以来destroy()

源语言

我认为你应该使用

child.dispose();

而不是使用 jQuery 删除标签。

另请参阅角度 2 - 动态添加/删除组件

您可以在ComponentRef类上使用 dispose 方法来删除组件。

为此,您需要以这种方式将其提供给组件实例本身:

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