I'm building simple angular application. There are two modules as student and teacher. Here is how my project organized.
First when the user enters the application, I let them choose whether they are a teacher or student.
Depending on that choice, the user will be redirected to the corresponding module.
Here is my app.routing.ts
file.
import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {StudentModule} from './student/student.module';
import {TeacherModule} from './teacher/teacher.module';
import {HomeComponent} from './home/home.component';
const routes: Routes = [
{
path: '',
component: HomeComponent
},
{
path: 'student',
loadChildren: () => StudentModule
},
{
path: 'teacher',
loadChildren: () => TeacherModule
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
My problem is when I navigate into a module, I want to also navigate between components in the other module. Should I add another <router-outlet>
into each module, or can I do that with the <router-outlet>
in AppModule
.
If I should add another <router-outlet>
, how should I write my router class for those modules.
Lazy loading way Angular v8, v9 and Up
https://angular.io/guide/lazy-loading-ngmodules
// In app module route
{
path: 'your-path',
loadChildren: () => import('./path-to/your.module').then(m => m.YourModule)
}
// in your module
const yourRoutes: Routes = [
{ path: '', component: YourComponent }
];
export const yourRouting = RouterModule.forChild(yourRoutes);
@NgModule({
imports: [
yourRouting
],
declarations: [
YourComponent
]
})
export class YourModule{
}
Lazy loading way Angular v7, v6 and down
// In app module route
{
path: 'your-path',
loadChildren: 'app/your.module#YourModule'
}
// in your module
const yourRoutes: Routes = [
{ path: '', component: YourComponent }
];
export const yourRouting = RouterModule.forChild(yourRoutes);
@NgModule({
imports: [
yourRouting
],
declarations: [
YourComponent
]
})
export class YourModule{
}
Not lazy loading way
Just import the YourModule
in the main module and it will work if the routes are not lazily loaded.
@NgModule({
imports: [
BrowserModule,
FormsModule,
YourModule,
routing
],
declarations: [
AppComponent
],
providers: [
appRoutingProviders
],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
Take some time to read rout documentation https://angular.io/guide/router
Check this answer https://stackoverflow.com/a/39284277/6786941