2017-05-25 62 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); 
} 

如果知道如何改進此解決方案,請寫評論。我有這樣的感覺,那可能會更好。謝謝。