Introduction
The Angular router loads components into <router-outlet>. When the outlet shows nothing, the route configuration may be wrong, the router module not imported, or navigation not triggered properly.
Symptoms
Blank outlet:
<!-- Template renders but outlet is empty -->
<router-outlet></router-outlet>
<!-- Nothing displays, no component loaded -->No navigation:
// Clicking links does nothing
<a routerLink="/users">Users</a>
<!-- URL doesn't change, no navigation -->Console error:
Error: Cannot match any routes. URL Segment: 'users'
Error: No provider for Router!Common Causes
- 1.RouterModule not imported - Router not available
- 2.Missing routes - No route configuration provided
- 3.Wrong route path - Path doesn't match URL
- 4.Missing router-outlet - No outlet in template
- 5.Guards blocking - CanActivate returns false
- 6.Lazy loading failed - Module not loaded
- 7.Navigation not triggered - routerLink not working
Step-by-Step Fix
Step 1: Check RouterModule Import
```typescript // app.module.ts or app-routing.module.ts import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [ { path: 'users', component: UsersComponent }, { path: '', redirectTo: '/users', pathMatch: 'full' } ];
@NgModule({ imports: [ RouterModule.forRoot(routes), // Required! // or RouterModule.forRoot(routes, { enableTracing: true }) for debug // ... ], exports: [RouterModule] // Export for feature modules }) export class AppRoutingModule { }
// In feature module: @NgModule({ imports: [ RouterModule.forChild(routes), // Use forChild for features ] }) export class FeatureModule { } ```
Step 2: Verify Route Configuration
```typescript // Check routes are defined correctly const routes: Routes = [ // Basic route { path: 'users', component: UsersComponent },
// Default route { path: '', redirectTo: '/home', pathMatch: 'full' },
// Wildcard route (must be last!) { path: '**', component: NotFoundComponent },
// Route with parameter { path: 'user/:id', component: UserDetailComponent },
// Nested routes { path: 'admin', component: AdminComponent, children: [ { path: 'users', component: AdminUsersComponent }, { path: 'settings', component: AdminSettingsComponent } ] } ];
// Debug: Log routes console.log('Routes:', routes); ```
Step 3: Check Router Outlet
```html <!-- app.component.html --> <header> <nav> <a routerLink="/home" routerLinkActive="active">Home</a> <a routerLink="/users" routerLinkActive="active">Users</a> </nav> </header>
<!-- Primary outlet --> <router-outlet></router-outlet>
<!-- Named outlet for secondary routes --> <router-outlet name="popup"></router-outlet>
<!-- Common mistakes --> <!-- WRONG: Missing router-outlet --> <div class="content"> <!-- No outlet! Routes won't render --> </div>
<!-- CORRECT: Include outlet --> <div class="content"> <router-outlet></router-outlet> </div> ```
Step 4: Test Navigation
```typescript // Test navigation programmatically export class AppComponent { constructor(private router: Router) { // Debug: Log navigation events router.events.subscribe(event => { console.log('Router event:', event); }); }
navigateToUsers() { // Programmatic navigation this.router.navigate(['/users']); // or this.router.navigateByUrl('/users'); } }
// Template navigation <a routerLink="/users">Users</a> <!-- vs --> <a [routerLink]="['/users']">Users</a> <!-- With binding -->
// With parameters <a [routerLink]="['/user', userId]">User</a> this.router.navigate(['/user', userId]);
// With query parameters this.router.navigate(['/users'], { queryParams: { page: 1, sort: 'name' } }); ```
Step 5: Enable Router Tracing
```typescript // Enable tracing for debugging @NgModule({ imports: [ RouterModule.forRoot(routes, { enableTracing: true, // Log navigation events to console useHash: false, // Use HTML5 history initialNavigation: true }) ] }) export class AppRoutingModule { }
// Check browser console for: // Router Event: NavigationStart // Router Event: RoutesRecognized // Router Event: NavigationEnd ```
Step 6: Check Route Guards
```typescript // Guards can block navigation const routes: Routes = [ { path: 'admin', component: AdminComponent, canActivate: [AuthGuard], // Can block navigation canActivateChild: [AuthGuard], canLoad: [AuthGuard] // Can block lazy loading } ];
// Check if guard is blocking @Injectable() export class AuthGuard implements CanActivate { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { console.log('AuthGuard checking:', state.url); const isAuthenticated = this.authService.isLoggedIn(); console.log('Is authenticated:', isAuthenticated); return isAuthenticated; } }
// Temporarily disable guard for testing canActivate: [] // No guards ```
Step 7: Fix Lazy Loading
```typescript // app-routing.module.ts const routes: Routes = [ { path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) // Make sure path matches feature module routes } ];
// admin/admin-routing.module.ts const routes: Routes = [ { path: '', component: AdminDashboardComponent }, // /admin { path: 'users', component: AdminUsersComponent } // /admin/users ];
@NgModule({ imports: [RouterModule.forChild(routes)] }) export class AdminRoutingModule { }
// Check lazy loading in network tab // Should see admin-admin-module.js loaded when navigating to /admin
// Debug lazy loading this.router.events.pipe( filter(event => event instanceof LoadChildren) ).subscribe((event: LoadChildren) => { console.log('Lazy loading:', event); }); ```
Step 8: Check Base Href
```html <!-- index.html --> <head> <!-- Required for HTML5 routing --> <base href="/">
<!-- If app is in subdirectory --> <base href="/app/"> </head>
<!-- Or configure in Angular CLI --> // angular.json { "projects": { "your-app": { "architect": { "build": { "options": { "baseHref": "/" } } } } } } ```
Step 9: Handle Route Errors
```typescript // Catch navigation errors this.router.events.pipe( filter(event => event instanceof NavigationError) ).subscribe((event: NavigationError) => { console.error('Navigation error:', event.error); });
// Handle wildcard route const routes: Routes = [ // ... other routes { path: '**', component: PageNotFoundComponent } ];
// PageNotFoundComponent
@Component({
template:
<h2>Page not found</h2>
<p>The page "{{ url }}" does not exist.</p>
<a routerLink="/">Go home</a>
})
export class PageNotFoundComponent {
url = this.router.url;
constructor(private router: Router) {}
}
```
Step 10: Debug with Router State
```typescript // Access current route info export class AppComponent { constructor( private router: Router, private route: ActivatedRoute ) { // Current URL console.log('Current URL:', this.router.url);
// Route params this.route.params.subscribe(params => { console.log('Route params:', params); });
// Query params this.route.queryParams.subscribe(params => { console.log('Query params:', params); });
// Route data this.route.data.subscribe(data => { console.log('Route data:', data); });
// Full router state this.router.events.subscribe(event => { if (event instanceof NavigationEnd) { console.log('Navigation ended at:', event.url); } }); } } ```
Router Debugging Checklist
| Check | Command/Code |
|---|---|
| Routes defined | console.log(routes) |
| Router events | enableTracing: true |
| Current URL | this.router.url |
| Active route | this.route.snapshot |
| Navigation | router.navigate(['/path']) |
Verification
```bash # After fixing router configuration
# 1. Build should succeed ng build
# 2. Start dev server ng serve
# 3. Check console for router events # Should see: NavigationStart, RoutesRecognized, NavigationEnd
# 4. Navigate to routes # Click links or enter URLs directly # Components should load in router-outlet
# 5. Check network tab (for lazy loading) # Should see module chunks loading on demand
# 6. Test all routes ng test --include='**/*routing*.spec.ts' ```
Prevention
To prevent Angular router outlet not loading issues from recurring, implement these proactive measures:
1. Enable Router Tracing in Development
```typescript // app-routing.module.ts @NgModule({ imports: [RouterModule.forRoot(routes, { enableTracing: true, // Log router events to console paramsInheritanceStrategy: 'always' })], exports: [RouterModule] }) export class AppRoutingModule { }
// Disable in production export class AppRoutingModule { static forRoot() { return RouterModule.forRoot(routes, { enableTracing: !environment.production }); } } ```
2. Implement Route Guards Properly
```typescript // Auth guard with proper return @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor(private auth: AuthService, private router: Router) {}
canActivate(): Observable<boolean | UrlTree> { return this.auth.isAuthenticated$.pipe( map(isAuth => isAuth ? true : this.router.createUrlTree(['/login'])) ); } }
// Always return boolean or UrlTree, never void ```
3. Test Routes in Unit Tests
```typescript describe('Routing', () => { it('should navigate to users', fakeAsync(() => { const router = TestBed.inject(Router); const location = TestBed.inject(Location);
router.navigate(['/users']); tick();
expect(location.path()).toBe('/users'); })); }); ```
Best Practices Checklist
- [ ] Enable router tracing in development
- [ ] Implement proper route guards
- [ ] Test routes in unit tests
- [ ] Handle navigation errors
- [ ] Document route structure
- [ ] Use lazy loading for features
Related Issues
- [Fix Angular Module Not Found](/articles/fix-angular-module-not-found)
- [Fix Angular Dependency Injection Error](/articles/fix-angular-dependency-injection-error)
- [Fix Angular Component Not Rendering](/articles/fix-angular-component-not-rendering)
Related Articles
- [Technical troubleshooting: Fix Browser Back Button State Lost Spa Navigation ](browser-back-button-state-lost-spa-navigation)
- [Fix Cors Fetch Localhost Development Blocked Issue in Frontend](cors-fetch-localhost-development-blocked)
- [Fix Csp Violation Blocked Inline Script Style Issue in Frontend](csp-violation-blocked-inline-script-style)
- [Fix Angular Change Detection Loop](fix-angular-change-detection-loop)
- [Fix Angular Dependency Injection Error](fix-angular-dependency-injection-error)
<script type="application/ld+json"> { "@context": "https://schema.org", "@type": "TechArticle", "headline": "Fix Angular Router Outlet Not Loading", "description": "Troubleshoot Angular router-outlet not loading. Check route configuration, imports, and navigation triggers.", "url": "https://www.fixwikihub.com/fix-angular-router-outlet-not-loading", "publisher": { "@type": "Organization", "name": "FixWikiHub", "url": "https://www.fixwikihub.com" }, "author": { "@type": "Person", "name": "FixWikiHub Editorial Team" }, "datePublished": "2026-04-04T03:09:29.599Z", "dateModified": "2026-04-04T03:09:29.599Z" } </script>