Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring multiple components within @ngModule in Angular 2

Tags:

angular

I am developing a large application using Angular 2 and ASP.net MVC. I have approximately 120 components in my application which are all declared in @ngModule declarations block:

@NgModule({
  imports: [CommonModule],
  declarations: [Component1, Component2, Component3, ..., Component120]
})

Is there a mechanism where I can shorten this?

like image 880
shabari Avatar asked Nov 22 '16 10:11

shabari


People also ask

What is ngmodule in angular?

You also learned about Angular modules, which is a way to organize an application and extend it with capabilities from external libraries. Angular modules provide a compilation context for their components. The root NgModule always has a root component that is created during bootstrap.

How do I declare every component in an angular app?

Every component must be declared in one—and only one—Angular module. Open app.module.ts in your editor and import the HeroDetailComponent so you can refer to it. Add HeroDetailComponent to the module's declarations array. In general, the declarations array contains a list of application components, pipes, and directives that belong to the module.

What is a module in angular?

A module is a collection of components, services, directives and pipes (I will talk more about pipes and directives later). We use this to group a set of functionality in the app, and can export or import other modules as needed. Angular module is one of the fundamental building blocks in Angular.

How to create nested component in Angular 2?

Nest the SearchBar component inside the StudentList component Open the existing student.component.html file from app -> student folder and added the below code as highlighted, In the above code, you can see how it has been nested with the StudentList component. This is how we can create nested component in Angular 2.


1 Answers

You can build a shared module and add the components to this module, then you only have to add the shared module to imports: [MySharedModule] and all components and directives exported by MySharedModule become available to the importing module.

@NgModule({
  imports: [ CommonModule ],
  declarations: [ Component1,   Component2,   Component3....      Component120 
],
  exports: [ Component1,   Component2,   Component3....      Component120 ],
})

export class MySharedModule {}

@NgModule({
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  imports: [BrowserModule, MySharedModule]
})
class AppModule {}
like image 63
Günter Zöchbauer Avatar answered Oct 18 '22 02:10

Günter Zöchbauer