Search code examples
angularroutesangular2-routingangular18

Angular 18 - Route to nested components


I have a Login component which is the initial page. On the success of Login, it will route to the Home component which will hold 3 components: TopBar component which has a nav bar & 2 components save data & data list. My expected result is when the user clicks the "saveData" route on the nav bar, it should show the SaveData component; when the user clicks the "dataList" route it should show the Datalist page.

route.ts:

import { Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
import { SavedataComponent } from './savedata/savedata.component';
import { DatalistComponent } from './datalist/datalist.component';

const routeConfig: Routes = [
  { path: '', component: LoginComponent },   
  { path: 'home', component: HomeComponent,
    children: [
      { path: 'savedata', component: SavedataComponent },
      { path: 'satalist', component: DatalistComponent },
    ]
  }
];
export default routeConfig;

When the user clicks on the button on the Login component it is routed to the Home component.

home.component.html:

<app-topbar></app-topbar>
<section class="presentation">
  <app-savedata></app-savedata>
</section>

and topbar.html:

<ul class="navbar-nav">
  <li class="nav-item">
    <a class="nav-link active" aria-current="page" [routerLink]='["savedata"]'  routerLinkActive="active_route">Home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" [routerLink]='["datalist"]'  routerLinkActive="active_route" >List</a>
  </li>
</ul>

When I click on List on the nav bar it is not going to the List page. I can see in the console:

core.mjs:7191 ERROR RuntimeError: NG04002: Cannot match any routes. URL Segment: 'home/datalist'

What am I doing wrong? How do I get this to work?


Solution

  • There is a typo error in your datalist route. It should be "datalist" not "satalist".

    Besides, in your HomeComponent view you are rendering the DataListComponent by default. And when you click the datalist link, it will not display the DataListCompnent.

    You need the <router-outlet> element for displaying the component based on the selected route.

    import { RouterOutlet } from '@angular/router';
    
    @Component({
      selector: 'app-home',
      standalone: true,
      template: `
        <app-topbar></app-topbar>
        <section class="presentation">
            <router-outlet></router-outlet>
        </section>
      `,
      imports: [TopBarComponent, RouterOutlet],
    })
    export class HomeComponent {}
    

    Demo @ StackBlitz