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

时间:2018-02-27 15:33:12

标签: angular plunker

我在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 {}

谢谢!

1 个答案:

答案 0 :(得分:0)

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