繁体   English   中英

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

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

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

我是这样做的:

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

更新

自beta.16起,.dispose .dispose()destroy()

原版的

我想你应该用

child.dispose();

而不是使用jQuery删除标签。

另请参阅Angular 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();
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM