正如您所知,在早期版本的 Angular 中,可以在 ComponentFactoryResolver
的帮助下创建动态组件。作为
export class DialogService {
dialogComponentRef: ComponentRef<DialogComponent>
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private appRef: ApplicationRef,
private injector: Injector
) {}
appendDialogComponentToBody() {
// logic to add component using `ComponentFactoryResolver` instance
}
}
但是现在ComponentFactoryResolver
最新版本已弃用。
是的,有一种方法(到目前为止我知道)我们可以使用以下代码片段创建动态组件
@ViewChild("viewContainerRef", { read: ViewContainerRef }) vcr!: ViewContainerRef;
但同样,这只适用于 component
,不与service
.
如有任何帮助,我们将不胜感激。
最佳答案
您应该能够使用从 @angular/core
导出的 createComponent
函数,
const componentRef = createComponent(MyComponent, {
environmentInjector: this.appRef.injector,
})
然后
this.appRef.attachView(componentRef.hostView); // and detach later
并且您应该很高兴没有 viewContainerRef
关于angular - 如何使用不使用 ComponentFactoryResolver 的服务创建动态组件,因为它在 Angular 中已被弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73786064/