2017-05-25 66 views
0

我被卡住了动态组件的破坏。我会很感激一些提示。 这里我的根组件,它完美地增加了一个页面从服务的一些组件上:这是由根组件添加Angular 2.如何动态创建的组件可以自行调用destroy方法?

/*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); 
}} 

这里我的孩子组成。它必须自毁:

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

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

+0

好的,我找到了一个解决方案。如果有人在这个问题上需要帮助,我会回答。 –

回答

1

好吧,我的解决方案使用消息服务。如果您不知道它的作用,请查看here。这很简单。首先,我将唯一的ID分配给任何动态组件。接下来,我会在地图上继续参考组件和他的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; 
    } 

其次,事件点击孩子的视图通过消息服务发送他的id给父母。考虑到在孩子中声明的“componentId:string”。但它是在父项中分配的!

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

private componentId: string; 

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

最后,我们的父母从消息服务接收id。接下来,它会在地图中查找孩子的参考。最后,我们调用native方法this.target.remove(“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); 
} 

如果知道如何改进此解决方案,请写评论。我有这样的感觉,那可能会更好。谢谢。