javascript - 如何删除由模板引用创建的组件?
问题描述
我正在尝试获取对从模板生成的组件的引用,以便以后可以手动销毁它。这可能吗?
在这个例子中,我有一个模板,然后我用createEmbeddedView
它来创建一个新实例,然后将它添加到当前视图中。这适用于我的意图。
我已经尝试过并且能够删除my-component
,但我不确定如何访问它。我知道我可以使用 直接访问该组件@ViewChildren()
,但是如何获取ComponentRef
该组件的 a 并销毁它以便将其从 DOM 中删除?
@Component({
template: `
<button (click)="open()"></button>
<ng-template #template let-message="message">
<my-component>{{message}}</my-component>
</ng-template>
`
})
export ExampleComponent {
@ViewChild('template')
template!: TemplateRef<object>;
@ViewChildren(MyComponent)
myComponents!: QueryList<MyComponent>;
constructor(
private viewContainerRef: ViewContainerRef
){ }
open() {
const template = this.template.createEmbeddedView({message: 'hello'});
this.viewContainerRef.insert(template);
}
}
如果从最后一个到第一个删除,则有效
我能够使用它来工作remove()
,但是这是一个好方法吗?
ngAfterViewInit() {
this.myComponents.changes.subscribe(() => {
this.myComponents.forEach((cmp, idx) => {
if (!cmp.isOpen) {
cmp.open();
let sub = cmp.closed.subscribe(() => {
this.viewContainerRef.remove(idx);
sub.unsubscribe();
});
}
});
});
}
解决方案
只需this.viewContainerRef.insert(template)
使用this.viewContainerRef.remove(0)
or还原this.viewContainerRef.remove(this.viewContainerRef.length - 1)
。这将卸载组件并释放内存,因为不会留下任何引用(const template
仅限于open
函数)
推荐阅读
- python - 使用 Python 请求将数据和文件发送到 Forge API
- python - 为什么 Python 对于“sum”或“and”等相同函数的行为会有所不同?
- asp.net-core - Serilog 在使用多个环境配置文件时会创建多个 MSSqlServer 日志
- python - 我使用 selenium 的 python 脚本不再工作了。Chrome驱动版本问题
- switch-statement - Scheme语言中的case命令
- javascript - 创建一个基于0到1920之间的mouseX位置返回从-10到10的数字的函数?
- ubuntu - MinGW 交叉编译器和 -fprofile-generate 在 14.04 之后停止在 Ubuntu 上工作
- python - 如何在多个窗口 Tkinter 程序中保持恒定布局?
- c# - 如何在同一网络之间连接到 UWP 应用
- ios - Xcode 11.3 无法为 iOS 13.3 设置目标,即该选项不存在