Angular 9 - 未找到 <component> 的组件工厂

Angular 9 - No component factory found for <component>

将 Angular 应用程序从版本 8 更新到版本 9 后,出现以下错误: No component factory found for <component>. Did you add it to @NgModule.entryComponents?

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

With Angular 9 Ivy is now the default rendering engine

...

If you have specified any entryComponents in your NgModules or had any uses of ANALYZE_FOR_ENTRY_COMPONENTS, you can remove them. They are no longer required with the Ivy compiler and runtime.

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

"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);
}

这是我的问题,但我在这里回答,因为看起来其他人也有同样的问题。

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

"angularCompilerOptions": {
  "enableIvy": false
}

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