angular - 如何使用不使用 ComponentFactoryResolver 的服务创建动态组件,因为它在 Angular 中已被弃用

标签 angular dynamic-components

正如您所知,在早期版本的 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

Docs

关于angular - 如何使用不使用 ComponentFactoryResolver 的服务创建动态组件,因为它在 Angular 中已被弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73786064/

相关文章:

angular - 如何修复需要流的地方的 "Error: You provided ' undefined'。你可以提供一个 Observable、Promise、Array 或 Iterable”?

angular - 上下文菜单在我的 ag-grid 中不起作用

html - 选择后无法接收 Angular 2 函数中的选项值

angular - *ngif - 如果某些东西变得可见则隐藏 div

angular - 无法在 Angular 4 中监视注入(inject)服务的方法