I have a problem with navigating to the component defined in a lazy loading module.
The component ListComponent
is defined under the path "test" (my-routing.module.ts - lazy loading module). Whenever I click on the Test button (test.component.html) I get the exception:
NG04002: Cannot match any routes. URL Segment: 'test'.
Why?
My app-routing.module.ts looks like this:
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-.module').then(x => x.MyRoutingModule);
const routes: Routes = [
{ path: '', component: TestComponent },
{ path: 'experiment', loadChildren: myModule },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
My my-routing.module.ts is:
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 },
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class MyRoutingModule { }
My test.component.html looks like this:
<div class="container">
<div class="row">
<div class="col-1">
<a [routerLink]="['test']"><button type="button" class="btn btn-primary">
Test</button></a>
</div>
</div>
</div>
If you read your app.routing.ts,
{ path: 'experiment', loadChildren: myModule },
All the routes in the MyRoutingModule
will start with path: "experiment/".
Hence, change the path "test" to "experiment/test".
<a [routerLink]="['experiment/test']">
<button type="button" class="btn btn-primary">
Test
</button>
</a>
Note that you can apply the [routerLink]
attribute to the <button>
element without needing the <a>
element.
<button type="button" class="btn btn-primary" [routerLink]="['experiment/test']">
Test
</button>