0%

angular-router-troubleshooting

1. Url changed but page not loaded

Reason: The <router-outlet> is not in the html template.
Solution: Add the <router-outlet> to the template file.

1
2
3
4
5
6
7
8
9
<!-- app.component.html -->
<nav>
<ul>
<li><a routerLink="/home">Home</a></li>
<li><a routerLink="/product">Product</a></li>
<li><a routerLink="/about">About</a></li>
</ul>
</nav>
<router-outlet></router-outlet> <!-- Add this line -->

2. ERROR RuntimeError: NG04002: Cannot match any routes. URL Segment: ‘login’

Reason: Route ‘login’ is not defined in the router configuration.
Solution: Add the route to the router configuration.

1
2
3
4
// app-routes.ts
const routes: Routes = [
{ path: 'login', component: LoginComponent },
]

Reason 2: You use canMatch guard in route configuration and the guard return false.
Solution: Make sure the guard returns true.

1
2
3
4
5
{
path: 'product',
loadComponent: () => import('./product/product.component').then(m => m.ProductComponent),
canMatch: [CanMatchGuard], // <-- CanMatchGuard return false cause this error.
},

3. NG8001: ‘router-outlet’ is not a known element

Reason: The RouterModule is not imported in the module.
Solution: Import the RouterModule in the module.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Module based component(app.module.ts)
import { RouterModule } from '@angular/router';
@NgModule({
imports: [RouterModule] // <-- Add this line
})

// Standalone component
import { RouterModule } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet], // <-- Add this line
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})