简体   繁体   中英

Angular 2/4: Share a component with lazy loaded module and its components

dashboard component is global component. users module is lazy loaded which contains login component. I want to access this dashboard component in the lazy loaded login component. How do I achieve it? I know we can use Shared module. But, I am not sure how to implement it exactly. Please, guide me through.

Dashboard.componenet.html

<div class="container-fluid">
  <div class="row">
    <div class="col-md-3">
      <p-menu [model]="menuItems"></p-menu>
    </div>
    <div class="col-md-9">

    </div>
  </div>
</div>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

//PrimeNG
import { MenuModule } from 'primeng/primeng';

//components
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';

const appRoutes = [
  { path: '', component: DashboardComponent },
  { path: 'users', loadChildren: 'app/users/users.module#UsersModule'}
]

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent
  ],
  imports: [
    BrowserModule,
    MenuModule,
    RouterModule.forRoot(appRoutes)
  ],
  exports:[DashboardComponent],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

users.module.ts

//Interfaces
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

//Components
import { LoginComponent } from './login/login.component';

const lazyRoutes = [
    {path:'login/login', component: LoginComponent}
]

@NgModule({
    declarations:[
        LoginComponent
        // DashboardComponent
    ],
    imports: [
        // AppModule,
        RouterModule.forChild(lazyRoutes)
    ],
    exports:[],
    providers: []
})

export class UsersModule {}

login.component.html

<dashboard></dashboard>[enter image description here][1]

In my code, I have a "Shell" component similar in concept to your dashboard. It looks like this:

shell component

<mh-menu></mh-menu>

<div class='container'>
    <router-outlet></router-outlet>
</div>

The <mh-menu> is the component containing the menu. Below the menu is a router outlet. I can then route any of my content to that router outlet so it appears below the menu and the menu appears on every page.

In my example, my products are a lazy loaded module, yet I'm able to route the product edit page into this primary router outlet. So the lazy loaded component appears with the menu.

Here is a picture:

在此处输入图片说明

I have a complete example here: https://github.com/DeborahK/MovieHunter-routing (though its movies and not products)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM