I have a HomeComponent that i want to show at / route
HomeComponent.hmtl
<header>
<div>
<h1>CommunityPost</h1>
</div>
<button mat-raised-button color="primary" (click)="onLogout()">Log Out</button>
</header>
<mat-divider></mat-divider>
<main>
<nav mat-tab-nav-bar [tabPanel]="tabPanel">
<a mat-tab-link routerLink="/users" (click)="activeLink = '/users'"
[active]="activeLink == '/users'" > COMMUNITY</a>
<a mat-tab-link routerLink="/posts" (click)="activeLink = '/posts'"
[active]="activeLink == '/posts'" > POSTS </a>
</nav>
<mat-tab-nav-panel #tabPanel>
<router-outlet></router-outlet>
</mat-tab-nav-panel>
</main>
In router-outlet i want to show the children routes
app-route
const routes: Routes = [
`enter code here`{path: '', component: HomeComponent, canActivate: [guardGuard], children:[
{path: 'posts', loadChildren: () => import('./posts/posts.module').then(m =>
m.PostsModule)},
{path: 'users', loadChildren: () => import('./user/user.module').then(m =>
m.UserModule)},
{path: '', redirectTo: 'users', pathMatch: 'full'},
]},
{path: 'login', component: LoginComponent},
{path: '**', component: NotFoundComponent},
];
users-route
const routes: Routes = [
{path: '', component: UsersListComponent},
{path: 'users/:id', component: UserDetailComponent},
];
This show in / route the UserListComponent instead of HomeComponent and the UserList nested in it
Edit HomeComponent.ts
import { Component } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrl: './home.component.css'
})
export class HomeComponent {
activeLink: string
constructor(private router: Router){
this.router.events.subscribe((data: NavigationEnd)=> {
if(data.url !== undefined){
this.activeLink=data.url
}
})
}
onLogout(){
if(window.confirm('You are logging out. Are you sure?')){
localStorage.removeItem('auth')
window.location.reload()
}
}
}
If i go to localhost/ it will show only UserListComponent , but when I go to localhost/users it will show HomeComponent and the nested UsersListComponent as it shlould be
stackblitz to all project: https://stackblitz.com/~/github.com/DoublEffe/communitypost
UPDATE
I finally found the problem to your issue, you are importing
UserModuleandPostsModulein theAppModuleonce I removed this everything worked fine!Key takeaway!
Lazy loaded modules need not be imported on the main module, this will only cause routing issues!
stackblitz
Actually the code shared, did not have any major issues, I think the problem might be on the root component level, please check the below stackblitz for reference, if still facing issues, please share back the stackblitz with the issue replicated and details on what needs fixing!
home component!
Stackblitz Demo