2017-08-25 54 views
1

關閉按鈕,這是我的parent.html角2:刪除子組件上點擊相應的組件

parent.html 
<h1>Test for dynamic component</h1> 
<button (click)="addBox('BoxOneComponent')">AddBoxOne</button> 
<button (click)="addBox('BoxTwoComponent')">AddBoxTwo</button> 
<div> 
    <ng-template #parent></ng-template> 
</div> 

這裏是它的組成部分。

export class AppComponent implements AfterContentInit,OnInit { 
    @ViewChild('parent',{read:ViewContainerRef}) parent; 

    public resolve; 

    constructor(private cfr:ComponentFactoryResolver){} 

    addBox(val){ 
    let data; 
    switch(val){ 
     case "BoxOneComponent": 
     data = BoxOneComponent; 
     break; 
     case "BoxTwoComponent": 
     data = BoxTwoComponent; 
     break; 
    } 
    this.resolve = this.cfr.resolveComponentFactory(data); 
    this.parent.createComponent(this.resolve); 
    } 

    ngOnInit(){ 

    } 


    ngAfterContentInit(){ 

    } 

} 

這是我的孩子組成

import { Component, Input } from '@angular/core'; 

@Component({ 
    selector: 'box-one', 
    template: ` 
    <div> 
     <button (click)="delete()">Close</button> 
    </div> 
    `, 
    styles: [` 
    div{ 
     height:100px; 
     width:100px; 
     background-color:yellow; 
     display:inline-block; 
    } 
    button{ 
     margin-left:50px; 
    } 
    `] 
}) 
export class BoxOneComponent { 


} 

我能夠動態地添加組件。現在,我想通過單擊相應子組件中存在的按鈕來動態刪除子組件。我知道我們必須使用ViewContainerRef.remove(child的索引)。但是如何通過引用父類來獲取子組件的索引?

演示:Working Demo

回答

0

您的動態組件需要以某種方式通知,它應該被刪除父組件。我可以想到的最簡單的方法是在父組件可以訂閱的組件實例中提供Obseravble(承諾也可以)。

對於類型安全性,您還可以爲這些組件創建一個接口(指定它們必須在內部具有可觀察的close$)。


<button (click)="close()">Close</button> 

public close$ = new Subject<void>() 
public close() { 
    this.close$.next(null) 
} 

家長

const cmp: ComponentRef<any> = this.parent.createComponent(this.resolve); 
cmp.instance.close$.take(1).subscribe(() => cmp.destroy()) 

這裏有一個working demo

+0

謝謝,我有疑問。如何根據父母來獲取孩子的組成部分的索引? – Sampath1504

+0

爲什麼你需要索引?你的問題是如何刪除它們。 –

+0

如果我有父組件中的子組件的刪除按鈕。我需要一個子組件的索引來銷燬它的權利? – Sampath1504