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
谢谢,我有疑问。如何根据父母来获取孩子的组成部分的索引? – Sampath1504
为什么你需要索引?你的问题是如何删除它们。 –
如果我有父组件中的子组件的删除按钮。我需要一个子组件的索引来销毁它的权利? – Sampath1504