import { Component, effect, inject, signal } from '@angular/core';
import { Router, RouterState, NavigationEnd } from '@angular/router';
@Component({
template: `
<p>Current: {{ currentPath() }}</p>
<a routerLink="/dashboard">Dashboard</a>
<router-outlet />
`
})
export class AppComponent {
private router = inject(Router);
private routerState = inject(RouterState);
// Solution 1: Reactive router signal (Recommended)
currentPath = this.routerState.signal('url');
// Solution 2: Effect on router events (Side effects)
constructor() {
effect(() => {
this.router.events.pipe(filter((e): e is NavigationEnd => e instanceof NavigationEnd))
.subscribe(() => {
// Force signal read to trigger CD
this.currentPath();
});
});
}
// Solution 3: Manual CD trigger (Legacy)
onNavigate() {
this.cdr.markDirty(); // Only if no signals used
}
}