routerLink doesn't navigate to lazy loading modules for a named router outlet

75 Views Asked by At

I am trying to navigate to the component defined in a lazy loading module using the named router-outlet. When I click on the Test button (test.component.html) I get the exception:

NG04002: Cannot match any routes. URL Segment: 'test'.

My app-routing.module.ts is:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
import { AboutComponent } from './components/about/about.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { AuthGuard } from './auth.gard';
import { ListComponent } from './list.component';
import { TestComponent } from './test/test.component';


const myModule = () => import('./my-routing/my-routing.module').then(x => x.MyRoutingModule);
const routes: Routes = [
  { path: '', component: TestComponent },
  { path: 'experiment', loadChildren: myModule },
  {
    path: 'home',
    component: HomeComponent, outlet: "outlet1"
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

My test.component.html looks like this:

<div class="container">
  <div class="row">
    <div class="col-2">
      <a [routerLink]="[{ outlets:{ outlet1: ['home'] }}]" routerLinkActive="active"><button type="button" class="btn btn-primary">
          Home</button></a>
    </div>
    <div class="col-1">
      <a [routerLink]="[{ outlets:{ outlet1: ['experiment','test'] }}]"><button type="button" class="btn btn-primary">
          Test</button></a>
    </div>

  </div>
</div>

My my-routing.module.ts looks like:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ListComponent } from '../list.component';
import { TestComponent } from '../test/test.component';

const routes: Routes = [

  { path: 'test', component: ListComponent, outlet: "outlet1" },

];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class MyRoutingModule { }
1

There are 1 best solutions below

12
Yong Shun On

Change your [routerLink] as below for the auxiliary route.

<a [routerLink]="['experiment', { outlets:{ outlet1: ['test'] }}]">
    <button type="button" class="btn btn-primary">
        Test
    </button>
</a>

Demo @ StackBlitz