Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - Declaring a component in two different modules

Tags:

angular

I create DynamicForm component connect it in two NgModule.

//  Module 1
@NgModule({
    imports: [],
    exports: [],
    declarations: [
        DynamicForm
    ],
    providers: []
})

//  Module 2
@NgModule({
    imports: [],
    exports: [],
    declarations: [
        DynamicForm
    ],
    providers: []
})

But project dont work, any errors. When I remove DynamicForm from one of NgModule get error that I need include this component. Also I tryed connect DynamicForm to app.module and remove from NgModule and also did't work.

What to do?

like image 785
Станислав П Avatar asked Sep 28 '16 19:09

Станислав П


People also ask

Can a component be registered in multiple modules?

You can use same directives/components in multiple modules without errors.

Can we declare a component in multiple modules in Angular?

Shared modules are an ideal spot to declare components in order to make them reusable. You won't have to re-import the same components in every module—you'll just import the shared module. In this guide, you will learn how to use shared modules to organize your code more effectively.

How do I share a component between modules?

Sharing moduleslink You can put commonly used directives, pipes, and components into one module and then import just that module wherever you need it in other parts of your application. Notice the following: It imports the CommonModule because the module's component needs common directives.


1 Answers

Components can only be part of one module. For this reason, if you have a component that should be used by multiple modules, create a shared module, declare it there, then export so others can use it. Then import that shared module into the module where you need that component

@NgModule({
  declarations: [
    DynamicForm
  ],
  exports: [
    DynamicForm
  ]
})
export class SharedModule {}

@NgModule({
  imports: [ SharedModule ]
})
class ModuleThatNeedsDynamicForm {}
like image 169
Paul Samsotha Avatar answered Nov 15 '22 07:11

Paul Samsotha