【问题标题】:Angular 9 - No component factory found for <component>Angular 9 - 找不到 <component> 的组件工厂
【发布时间】:2020-06-12 00:09:06
【问题描述】:

将 Angular 应用程序从版本 8 更新到 9 后,我收到以下错误: No component factory found for &lt;component&gt;. Did you add it to @NgModule.entryComponents?

但正如Angular Update Guide 所述,不再需要向entryComponents 添加组件:

Angular 9 Ivy 现在是默认渲染引擎

...

如果你在你的 NgModules 中指定了任何 entryComponents 或者使用了 ANALYZE_FOR_ENTRY_COMPONENTS,你可以删除它们。 Ivy 编译器和运行时不再需要它们。

我正在使用以下软件包版本:

"dependencies": {
  "@angular/animations": "~9.0.3",
  "@angular/cdk": "~9.1.0",
  "@angular/common": "~9.0.3",
  "@angular/compiler": "~9.0.3",
  "@angular/core": "~9.0.3",
  "@angular/forms": "~9.0.3",
  "@angular/material": "^9.1.0",
  "@angular/platform-browser": "~9.0.3",
  "@angular/platform-browser-dynamic": "~9.0.3",
  "@angular/router": "~9.0.3",
},
"devDependencies": {
  "@angular-devkit/build-angular": "~0.900.3",
  "@angular-devkit/build-ng-packagr": "~0.900.3",
  "@angular/cli": "~9.0.3",
  "@angular/compiler-cli": "~9.0.3",
  "@angular/language-service": "~9.0.3",
}

这是我用来动态创建组件的代码:

@ViewChild('target', {static: true, read: ViewContainerRef}) target: ViewContainerRef;
@Input() componentType: Type<Component>;

cmpRef: ComponentRef<Component>;

constructor(private componentFactoryResolver: ComponentFactoryResolver) {}

ngOnInit() {
  this.updateComponent();
}

ngOnChanges() {
  this.updateComponent();
}

ngOnDestroy() {
  if (this.cmpRef) {
    this.cmpRef.destroy();
  }
}

updateComponent() {
  if (this.cmpRef) {
    this.cmpRef.destroy();
  }

  const factory = this.componentFactoryResolver.resolveComponentFactory(this.componentType);
  this.cmpRef = this.target.createComponent(factory);
}

【问题讨论】:

  • 你能把代码贴出来吗?
  • @developer033 我已经包含了我用来动态创建组件的代码。

标签: angular angular9


【解决方案1】:

这是我的错,但我在这里回答它,因为似乎其他人也有同样的问题。

虽然整个项目都更新到了 Angular 9,但 Ivy 在tsconfig.json 下被禁用了(我实际上在 Angular 8 上用 Ivy 做了一些测试,并没有意识到它被禁用了):

"angularCompilerOptions": {
  "enableIvy": false
}

我已通过删除enableIvy 设置启用它,问题已解决。

【讨论】:

    猜你喜欢
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2020-03-08
    • 2017-03-06
    相关资源
    最近更新 更多