I was implementing dynamic components for one of my project. The concept of dynamic components is that they come into the memory once they are needed and they have no reference in any template.
According to the official docs we declare such components in entryComponents
to prevent them from getting discarded in the tree shaking process as they have no template reference.
Following is the app.module.ts
where I have declared my two dynamic components SlideOneComponent
and SlideTwoComponent
in the entryComponents
array:
@NgModule({
declarations: [
AppComponent,
ButtonComponent,
AdDirective
],
imports: [
BrowserModule
],
providers: [],
entryComponents: [
SlideOneComponent,
SlideTwoComponent,
],
bootstrap: [AppComponent]
})
export class AppModule { }
With above app.module.ts
I am getting following error:
The above error fades away as soon as I add my both dynamic components to declarations
array. The aforementioned official docs also says that we do not need to declare components that are reachable from entryComponents
or bootstrap
component. I visited this answer as well but that does not seem to be satisfactory enough as it is in reference to Ionic.
Please help me to know where I am missing on this. Thanks in advance! :)
As seen in this quote (while reading between the lines):
Though the @NgModule decorator has an entryComponents array, most of the time you won't have to explicitly set any entry components because Angular adds components listed in @NgModule.bootstrap and those in route definitions to entry components automatically.
You add usual components to EntryComponents array implicitly, meaning they are added in both arrays - Declarations and EntryComponents (while you added it only in Declarations array). So you must add dynamic components explicitly to both arrays as well.
Declarations purpose is to make directive (component etc.) available for other classes in your module and match it's selector with HTML.
EntryComponents tells Angular to create a componentFactory, which is being created by a compiler from the metadata you provide in @Component
decorator, so you later can use it in createComponent()
.
As seen, these two arrays serve very different purposes and both are needed in order to create a component. If component is not created dynamically, compiler reads it's metadata and creates a componentFactory, but compiler is not aware of dynamic components, so you must inform it about dynamic components before it runs, as he runs only once - at compile time :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With