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