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

Posted

技术标签:

【中文标题】Angular2 - 删除所有/最近的子组件后无法添加子组件【英文标题】:Angular2 - Can't add child component after deleting all/recent child components 【发布时间】:2016-06-15 07:47:16 【问题描述】:

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

这是我的做法:

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

【问题讨论】:

你能在 plnkr 上预先制作它吗? angular.io/resources/live-examples/quickstart/ts/plnkr.html 【参考方案1】:

更新

.dispose()destroy() 从 beta.16 开始

原创

我认为你应该使用

child.dispose();

而不是使用 jQuery 删除标签。

另见Angular 2 - Adding / Removing components on the fly

【讨论】:

【参考方案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();
  
;

【讨论】:

以上是关于Angular2 - 删除所有/最近的子组件后无法添加子组件的主要内容,如果未能解决你的问题,请参考以下文章

删除元素后,子组件无法从其父组件获取数组。

渲染所有组件后,如何在 Angular2 中运行 TypeScript 代码?

Angular 2 - 无法解析组件的所有参数:(?)

从 Angular2 路由中的子组件调用 router.parent.navigate 方法时未触发组件构造函数和路由器生命周期挂钩

Angular 2父组件丢失来自子组件的输入绑定

formGroup的子组件内的Angular 2 formControlName