Angular 4 – How to pass value from parent component to child modules

Issue

I’m trying to pass the value from parent component to the child module. this is my project structure:

++Layout
---admin-layout.component.html
---admin-layout.component.ts
++Dashboard
---dashboard.component.html
---dashboard.component.ts
---dashboard.module.ts
---dashboard.routing.ts

and my app.routing.ts routing is something like this.

export const AppRoutes: Routes = [{
  path: '',
  component:  AdminLayoutComponent,
  children: [
    {path: '/dashboard', loadChildren: 'PATH/dashboard.module#DashboardModule'},
///
]}];

so my question I have a click event in admin-layout.html so how do I send the value from admin layout to dashboard?

currently, I’m sending it via Url something like changing it on the path

 {path: '/dashboard/:eventidvalue', loadChildren: 'PATH/dashboard.module#DashboardModule'},

when it is routed.

Is there any alternative and clean way of doing it.

Solution

you can use a Singleton service that has one instance, put some date in it and get them everywhere you need.
create a shared module after that create a sharedService and import your that shared modules in your main module and dashboard module

you can use ModuleWithProviders and forRoot to Provide a singleton service

import { SharedService } ...
...
export class SharedModule {
static forRoot(): ModuleWithProviders {
    return {
        ngModule: SharedModule,
        providers: [SharedService]
    }
}}

and you can import it that way:

imports: [
    SharedModule.forRoot(),
],

Answered By – Fateh Mohamed

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.