Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: Shared component thats used for routing

I am using a component for routing in 2 separate modules. Angular throws an error about 2 declarations. How can I make this shared?

Typical guides for shared components show how to share but not use in the module for routing.

I want to use the ProductComponent in 2 separate modules but the component is used for routing so typical shared component strategy doesn't work.

Routing :

EXAMPLE1.module.ts

`

...
import { ProductComponent } from '../../product/product.component';

export const routes:Routes = [
    { path: 'products/:product-slug',  component: ProductComponent },
    other example 1 routes
];

@NgModule({
    imports: [
        CommonModule,
        ...
    ],
    declarations: [
        ProductComponent,
        other example 1 components
    ],
    providers: [
        ...
    ]
})
export class EXAMPLE1 { }

`

EXAMPLE2.module.ts

`

...
import { ProductComponent } from '../../product/product.component';

export const routes:Routes = [
    { path: 'different/:product-slug',  component: ProductComponent },
    other example 2 routes
];

@NgModule({
    imports: [
        CommonModule,
        ...
    ],
    declarations: [
        ProductComponent,
        other example 2 components
    ],
    providers: [
        ...
    ]
})
export class EXAMPLE1 { }

`

The product component is shared amongst these 2 modules

Any ideas?

like image 385
Sean Avatar asked Nov 03 '25 05:11

Sean


1 Answers

you can export that component in your shared.module.ts like this

declarations: [ ProductComponent,
               ...
              ]
exports: [ ProductComponent],

after that you can import your shared module in the 2 modules

imports:[ 
        SharedModule,
      ]

so in your app.routing.ts you can import it and you dont need to declare it in the modules anymore, import your component in your both routing files, something like this

import { ProductComponent } from '../shared/product.component.ts'
like image 123
Fateh Mohamed Avatar answered Nov 06 '25 04:11

Fateh Mohamed