老话题,但因为我很难尝试同样的......
遗憾的是,组件无法自动删除自身
所以我们有以下选择。
1: 视图容器引用 https://angular.io/api/core/ViewContainerRef
您可以使用以下命令生成您的组件componentFactoryResolver
,将它们存储到一个数组中,然后使用这个数组来完全删除那些组件
<ng-template #chipsContainer></ng-template>
@ViewChild('chipsContainer', { read: ViewContainerRef, static: true })
chipsContainer: ViewContainerRef
loadedChips: any[] = []
addChip(attributes: any) {
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(
AppChipsComponent,
)
let componentRef = this.componentLoaderContainer.createComponent(componentFactory)
let ref: any = componentRef.instance
ref.init(this.loadedChips.lenght) // Will be used to know which index should be removed
this.loadedChips.push(componentRef)
// Subscribing to the EventEmitter from the chip
ref.emitDeletion
.subscribe((index: number) => {
this._removeChip(index)
})
}
private _removeChip(index: number) {
this.loadedChips[index].destroy()
this.loadedChips.splice(index, 1)
}
那么,您还应该在芯片组件中添加什么
export class AppChipsComponent {
private _index: number
@Output() emitDeletion = new EventEmitter<boolean>()
init(index: number) {
this._index = index
}
remove() {
this.emitDeletion.emit(this._index)
}
}
2:Javascript
如果第一个例子看起来很复杂(确实如此,如果你想听听我的意见'^^)你可以简单地添加一个id
到html或任何其他可以帮助您识别它的东西
然后,当点击remove()
你可以得到它,并正确删除它。
<!-- You can use an *ngFor to make it simpler -->
<app-chips id="appChips-0" [id]="appChips-0"></app-chips>
<app-chips id="appChips-1" [id]="appChips-1"></app-chips>
<app-chips id="appChips-2" [id]="appChips-2"></app-chips>
export class AppChipsComponent {
@Input() id!: string
remove() {
document.getElementById(this.id).remove()
}
}
Voilà.