我想从服务中添加动态组件。 我的组件是BubbleComponent。
import { BubbleComponent } from '@app/component/bubble';
import {SiplecService} from '@app/service/siplec.service';
@NgModule({
imports: [
FormsModule,
CommonModule,
NgbModule,
RouterModule.forChild(HomeRoutes),
],
declarations: [HomeComponent, BasketComponent, BubbleComponent],
entryComponents: [ BubbleComponent ],
providers: [ SiplecService ]
})
export class HomeModule {}
为我服务:
setRootViewContainerRef(viewContainerRef: any) {
this.rootViewContainer = viewContainerRef;
}
addDynamicComponent() {
const factory = this.factoryResolver
.resolveComponentFactory(BubbleComponent);
const component = factory
.create(this.rootViewContainer.parentInjector);
this.rootViewContainer.insert(component.hostView);
}
我收到以下错误:
错误错误:找不到BubbleComponent的组件工厂。您是否将其添加到@ NgModule.entryComponents? 在noComponentFactoryError(core.js:7409)
答案 0 :(得分:0)
您能否尝试下面的代码以查看其工作原理
@ViewChild("dynamicContainer", { read: ViewContainerRef }) container: ViewContainerRef;
componentRef: ComponentRef<BubbleComponent>;
constructor(private resolver: ComponentFactoryResolver) {}
createComponent(type) {
//Clear the container.
this.container.clear();
//Create a factory for component.
const factory = this.resolver.resolveComponentFactory(BubbleComponent);
//Create a component using the factory
this.componentRef = this.container.createComponent(factory);
}
还要确保您也导入了声明
@NgModule({
declarations: [
BubbleComponent
],