You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改使用已弃用ComponentFactoryResolver的Angular代码

移除ComponentFactoryResolver的修改方案

从Angular 13开始,ComponentFactoryResolver已被弃用,DomPortalOutlet的构造函数也不再需要该参数——Angular会通过注入的Injector自动处理组件工厂的解析逻辑。你可以按以下步骤修改代码:

修改要点

  • 删除attachComponent方法中的componentFactoryResolver参数
  • 实例化DomPortalOutlet时,移除第二个参数(原componentFactoryResolver)

修改后的完整代码

export class SidenavService {
  private sidenavPortalOutlet!: PortalOutlet;
  private componentRef!: ComponentRef<any>;

  constructor(private applicationRef: ApplicationRef) {}

  attachComponent(
    portal: ComponentPortal<any>,
    injector: Injector
  ): ComponentRef<any> {
    this.sidenavPortalOutlet = new DomPortalOutlet(
      document.querySelector("#sidenav-portal-outlet") as Element,
      this.applicationRef,
      injector
    );
    this.componentRef = this.sidenavPortalOutlet.attach(portal);

    return this.componentRef;
  }

  detachComponent(): void {
    this.componentRef.destroy();
    this.sidenavPortalOutlet.detach();
  }
}

补充说明

新版本的DomPortalOutlet构造函数中,componentFactoryResolver已被标记为可选且弃用参数,Angular内部会通过Injector自动获取组件工厂解析能力,直接省略该参数完全不影响原有功能逻辑。

内容的提问来源于stack exchange,提问作者igogra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 23:57:37