我已遵循此指南:https://angular.io/api/core/ViewContainerRef#createComponent
组件服务类:
@ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) rootViewContainer: ViewContainerRef;
addComponent(component: ComponentModel) {
if(!component) {
return;
}
let factory = this.componentFactoryResolver.resolveComponentFactory(component.component);
let newComponent: ComponentModel = <ComponentModel>this.rootViewContainer.createComponent(factory, component.window.index, this.injector).instance;
newComponent.window = component.window;
console.log(newComponent);}
remove(index: number) {
console.log(this.rootViewContainer.remove(index));
console.log(this.rootViewContainer.detach(index));}
dynamicComponentContainer:
<div #dynamicComponentContainer></div>
我想要实现的目标是什么? - 我想用按钮添加组件,这是有效的。我想要删除一个特定的组件,例如使用关闭按钮,它不会关闭所单击的组件,随机按下其中一个打开的组件。
我做错了什么?
提前致谢。
答案 0 :(得分:0)
您的代码有点令人困惑(没有钩子,没有构造函数)但是您有一个ComponentFactoryResolver
类型的组件工厂,所以您的构造函数如下所示:
constructor(
private resolver: ComponentFactoryResolver
) {}
我假设您正在ngAfterContentInit
挂钩内初始化该工厂:
ngAfterContentInit() {
const factory= this.resolver.resolveComponentFactory(AComponent);
this.component = this.dynamicComponentContainer.createComponent(factory);
}
以上,this.component
实际上是ComponentRef
,AComponent
是您要操作的组件:
import { AComponent } from './a.component';
export class MainComponent implements AfterContentInit {
component: ComponentRef<AComponent>;
您还拥有ViewContainerRef
:
@ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) dynamicComponentContainer: ViewContainerRef;
既然this.component
是ComponentRef
,你就可以销毁它:
destroyComponent() {
this.component.destroy();
}