0
votes

I try to achieve lazy module loading but I don't succeed yet.
I want when the user go to /admin - then the AdminModule will start,
and when the user go to /admin/user - then UserComponenet of AdminModule will start.

This is the folder structure of my app:
app folder structure

In my app I have AppModule:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';

const routes: Routes = [
  {path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) }
 ];

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }


AppComponent html file:

--- App Componenet --- <br /><br />
<a routerLink="admin">admin</a><br />
<a routerLink="admin/home">admin/home</a><br />
<a routerLink="admin/user">admin/user</a><br />

<br /><br />
Router outlet result: <br />
<router-outlet></router-outlet>


AdminModule file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { UserComponent } from './user.component';

const routes: Routes = [
    { path: 'home', component: HomeComponent },
    { path: 'user', component: UserComponent },
    { path: '', component: HomeComponent }
];

@NgModule({
  declarations: [
    HomeComponent,
    UserComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forChild(routes)
  ]
})
export class AdminModule { }


HomeComponent html file:

Home Works!


UserComponent html file:

User Works!

What am I do wrong? Thanks.

1
Is this angular 8 or 9? by "then UserComponenet of AdminModule will start." you mean that the UserComponent will be downloaded to the browser? - Raz Ronen
angular 9. I mean I want to UserComponent to be loaded. - matan___4
see Manually Load Angular Component in here: mokkapps.de/blog/… - Raz Ronen
Do you want to lazy load user component only when the admin/user is activated? Then you may want to look at lazy load components. What you are doing is just a lazy loading of modules which will load all the components within the module when any of the admin routes is activated. - Amit Chigadani

1 Answers

1
votes

try to change AdminModule as follow

import CommonModule intead of BrowserModule

@NgModule({
  declarations: [
    HomeComponent,
    UserComponent
  ],
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ]
})
export class AdminModule { }

example