未找到未定义的组件工厂。但确实添加到@NgModule.entryComponents

No component factory found for undefined. but did add to @NgModule.entryComponents

我在 Plunker 的控制台中收到以下错误:

未找到未定义的组件工厂。您是否将其添加到@NgModule.entryComponents?

但我确实将组件 (SecondComp) 添加到 @NgModule 中的 entryComponents 中。请查看此 plnkr 并告诉我,为什么我会收到此错误?

https://plnkr.co/edit/BM3NMR?p=preview

//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {FirstComp} from './first.component'
import {SecondComp} from './second.component'
import {InjService} from './inj.service'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
    <first-comp></first-comp>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
}

@NgModule({
  imports: [ BrowserModule ],
  providers: [ InjService ],
  declarations: [ App, FirstComp, SecondComp ],
  bootstrap: [ App ],
  entryComponents: [ SecondComp ],
})

export class AppModule {}

谢谢!

您的 inj.service.ts 中存在简单的拼写问题。您将 SecondComp 拼写为 SecondComponent。将 SecondComponent 更改为 SecondComp 解决了这个问题,同时取消了 addDynamicComponent 方法中的行注释。

inj.service.ts:

之前

import {SecondComponent} from './second.component' // <- Over here

// ...

addDynamicComponent() {
  const factory = this.factoryResolver.resolveComponentFactory(SecondComp)
//  const component = factory.create(this.rootViewContainer.parentInjector)
//  this.rootViewContainer.insert(component.hostView)
}

之后

import {SecondComp} from './second.component' // <- Over here

// ...

addDynamicComponent() {
  const factory = this.factoryResolver.resolveComponentFactory(SecondComp)
  const component = factory.create(this.rootViewContainer.parentInjector)
  this.rootViewContainer.insert(component.hostView)
}

Updated Plnkr