Angular 2 multiple components declaration

5k views Asked by At

I'm working on a generic Ionic 2 app which consist in loading and displaying multiple components on the first page.

Each add-ons need to be easily created and implemented in the app very easily. So I created a file named "addon-declaration.ts". Inside this file, I exported all my components :

export { MyFirstAddon } from './components/addon1/first.addon';
export { MySecondAddon } from './components/addon2/second.addon';
export { MyThirdAddon } from './components/addon3/third.addon';

So my question is how to import all my components directly on "app.module.ts" declarations field ?

I already tried this but it's not working :/

import * as ModuleHandler from '../models/addons/addon-declaration';

@NgModule({
  declarations: [
    MyApp,
    ModuleHandler <--- Not working
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}]
})
export class AppModule {}

It's working nice if I import them one by one :

import { MyFirstAddon } from'../components/addon1/first.addon';
import { MySecondAddon } from'../components/addon2/second.addon';
import { MyThirdAddon } from'../components/addon3/third.addon';

@NgModule({
      declarations: [
        MyApp,
        MyFirstAddon, <--- Working well
        MySecondAddon,
        MyThirdAddon
      ],
3

There are 3 answers

0
Günter Zöchbauer On BEST ANSWER

Create a feature module that exports your components and directives

@NgModule({
  declarations: [MyFirstAddon, MySecondAddon, MyThirdAddon],
  exports: [MyFirstAddon, MySecondAddon, MyThirdAddon]
})
export class MyAddonModule {}

Add that module to imports of other modules where you want to use your addons

import { MyAddonModule } from './components/my-addon-module';

@NgModule({
  declarations: [
    MyApp,
    ModuleHandler <--- Not working
  ],
  imports: [
    IonicModule.forRoot(MyApp), MyAddonModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}]
})
0
Jasper de Jager On
declarations: [
   MyApp,
   ModuleHandler.MyFirstAddon,
   ModuleHandler.MySecondAddon,
   ModuleHandler.MyThirdAddon
]

or use ngModule that exports them and import the module.

0
Shobhit Sharma On

Create a index.ts inside that folder where your all addon files are placed and then export all files like :

export * from './first.addon';
export * from './second.addon';
export * from './third.addon';
.....

then after you need to import all the addons files in your app.module.ts like :

import * as allAddons from './addons_files';

at the end you need to use allAddons object like :

@NgModule({
    declarations: [
      // all-addons
      allAddons.FirstAddon,
      allAddons.SecondAddon,
      allAddons.ThirdAddon
    ]
})
export class AppModule() {
}