angular2-components - Angular 2.动态创建的组件如何自行调用destroy方法?

标签 angular2-components

我被动态组件的破坏所困扰。如果有一些提示,我将非常感激。 这是我的根组件,它在页面上完美地添加了服务中的一些组件:

/*Root*/
@Component({
selector: 'convertors',
template: "<div #target></div>"})

export class AppComponent {
@ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef;

private componentRef: ComponentRef<any>;
constructor(private componentFactoryResolver: ComponentFactoryResolver,
            private viewContainerRef: ViewContainerRef){}

addComponent(){
    let someComponent = this.service.getService("someComponent");
    const factory = this.componentFactoryResolver.resolveComponentFactory(someComponent);
    this.componentRef = this.target.createComponent(factory);
}}

这是我的子组件,由根组件添加。它必须 self 毁灭:

@Component({
selector: 'convertors',
template: "<button (click)="deleteComponent()" >Delete</button>"})
export class someComponent{
    deleteComponent(){
    /*How could I implement this function?*/
    }
}

我如何实现方法deleteComponent()? 谢谢!

最佳答案

好的,我的解决方案使用消息服务。看here如果你不知道它的作用。这很简单。 首先,我为任何动态组件分配唯一的 id。接下来,我在 map 中保留组件及其 ID 的引用。

  private componentRef: ComponentRef<Component>;

  onComponent(event: string){
    let component = "ref to any component"
    const factory = this.componentFactoryResolver.resolveComponentFactory(component);
    let componentRef = this.target.createComponent(factory);
    let id = "id" + this.index;
    (<any>componentRef.instance).componentId = id;
    this.idMap.set(id, componentRef);
    this.componentRef = componentRef;
    this.index += 1;
  }

其次, subview 上的事件点击通过消息服务将其 id 发送给父 View 。考虑到在子级中声明的“componentId:string”。但它是在父级中分配的!

<a (click)="deleteComponent()"></a>

private componentId: string;

deleteComponent() : void {
    this.messageService.sendMessage(this.componentId);
}

最后,我们的父级从消息服务接收 id。接下来,它在 map 中查找 child 的引用。最后,我们调用原生方法 this.target.remove("child index in componentRef") 来删除组件。考虑到,该 componentRef 有他自己的子项索引。

this.subscription = this.messageService.getMessage()
    .subscribe(message => this.removeChild(message))

removeChild(message){
    let component = this.idMap.get(message.id);
    let indice = this.target.indexOf(component);
    this.target.remove(indice);
    this.idMap.delete(message.id);
}

如果知道如何改进这个解决方案请写在评论中。我有一种感觉,它可能会更好。谢谢。

关于angular2-components - Angular 2.动态创建的组件如何自行调用destroy方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44187651/

相关文章:

angular2-template - Angular 2 扩展组件 - 如何继承样式

Angular 2子组件检查父组件

css - Amcharts:如何在 valueAxis svg 元素中应用变换

angularjs - 在 Jquery 插件模板中绑定(bind) Angular2 组件

angular - 是否可以在 Angular 2 中手动实例化组件

angular - 使用 Webpack 将外部 less 文件导入到 app.component.less 文件中

angular - 通过组件Angular 2中的选择器传递参数

angular - 使用 Angular2 中的服务在组件之间共享数据

angular - ionic2 rc0 中找不到组件工厂错误

ionic-framework - 在 Ionic 2 中,如何创建使用 Ionic 组件的自定义组件?