2017-08-25 53 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