What is entryComponents in angular ngModule?

raj picture raj · Sep 28, 2016 · Viewed 77.6k times · Source

I am working on an Ionic app ( 2.0.0-rc0 ) which depends on angular 2 . So the new introduction of ngModules is included. I am adding my app.module.ts. below.

import { NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { Users } from '../pages/users/users';

@NgModule({
  declarations: [
    MyApp,
    Users
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    Users
  ]
})
export class AppModule {}

What does entryComponents do here? Components are already defined in declarations . So what's the need of repeating them ? What would happen if I dont include a component here?

Answer

Günter Zöchbauer picture Günter Zöchbauer · Sep 28, 2016

This is for dynamically added components that are added using ViewContainerRef.createComponent(). Adding them to entryComponents tells the offline template compiler to compile them and create factories for them.

The components registered in route configurations are added automatically to entryComponents as well because router-outlet also uses ViewContainerRef.createComponent() to add routed components to the DOM.

Offline template compiler (OTC) only builds components that are actually used. If components aren't used in templates directly the OTC can't know whether they need to be compiled. With entryComponents you can tell the OTC to also compile this components so they are available at runtime.

What is an entry component? (angular.io)

NgModule docs (angular.io)

Defines the components that should be compiled as well when this component is defined. For each components listed here, Angular will create a ComponentFactory and store it in the ComponentFactoryResolver.

If you don't list a dynamically added component to entryComponents you'll get an error message a bout a missing factory because Angular won't have created one.

See also https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html