الانتقال إلى المحتوى
FrontendAngular· 7 دقائق للقراءة

Same Route, New :id, Same Component: Why ngOnInit Doesn't Run Again

When only the parameters change, the router keeps the component you already have. Read the id as a signal, not once in ngOnInit.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • Angular 22
محتويات المقال

The user profile page has a "People you may know" list at the bottom. Click a name, and the address bar changes from /users/1 to /users/2, but the page still shows the first user's name, photo and posts. Press F5 and it's suddenly correct. QA files it as intermittent, because it never happens when you arrive from the user list or type the URL by hand. The component reads the id once, in ngOnInit, from route.snapshot, and ngOnInit doesn't run a second time.

The common misconception

The belief: every navigation to a new URL destroys the current page component and creates a fresh one, so ngOnInit runs again with the new id. "Init" sounds like "page load", and a component looks like a page.

Most of the time, the app behaves exactly that way. Users usually move between different routes: from the list to a detail page, from the detail page to settings. Each of those does create a new component, and tutorials read this.route.snapshot.paramMap.get('id') in ngOnInit for precisely that flow. Typing a URL or pressing F5 reloads the whole app, which creates everything again. The only path that exposes the difference, a link from one detail page to another of the same kind, is also the one nobody tests first.

What actually happens

The router compares route configs, not URLs

On every navigation the router asks its whether it can keep each active route. The default, BaseRouteReuseStrategy, reuses a route when the matched router config is identical. /users/1 and /users/2 both match the same { path: 'users/:id' } entry, so the existing component stays. The API docs spell out the purpose: the component isn't destroyed and recreated when only the route parameters, query parameters or fragment change.

Reuse means none of the creation code runs. No constructor, no field initializers, no ngOnInit, and no ngOnDestroy for the old one either. What does change is the route state the component can observe: the ActivatedRoute stays the same object, and its params, paramMap, queryParams and data Observables emit the new values.

A snapshot is a photo

The route guide describes snapshots as static: they don't reflect future changes. Reading route.snapshot.paramMap.get('id') gives you the id at that moment, as a plain string, and nothing tells your code when the URL moves on. Read it once in ngOnInit, and the component keeps loading, displaying and saving user 1 while the address bar says 2.

Local state survives, too

It's not only the id. Anything the component holds stays as it was: the selected tab, an open panel, a half-edited form, a scroll position inside the component. Often that's exactly what you want, and reuse gives it to you for free. But state that belongs to one user has to be reset when the id changes, for example with a whose source is the id.

Resolvers rerun; snapshot reads don't

Guards and resolvers do run again. With the default runGuardsAndResolvers policy, paramsChange, the router reruns them when path or matrix parameters change, though not for query parameters. So a resolver fetches user 2 correctly, and a component that reads route.snapshot.data once in ngOnInit still never sees the result.

The fix: read the id as a signal

The fix is to stop treating the id as something you read once and start treating it as a that changes. Enable input binding with provideRouter(routes, withComponentInputBinding()), and the router sets component inputs from path, matrix and query parameters, static route data and resolver data, by matching their names. When a key disappears from the route, the input is set to undefined, so old values don't linger.

TypeScript user-page.ts
import { HttpClient } from '@angular/common/http';import { Component, inject, OnInit, signal } from '@angular/core';import { ActivatedRoute } from '@angular/router';@Component({  selector: 'app-user-page',  template: `<h1>{{ user()?.name }}</h1>`,})export class UserPage implements OnInit {  private readonly route = inject(ActivatedRoute);  private readonly http = inject(HttpClient);  readonly user = signal<User | undefined>(undefined);  ngOnInit() {    // Runs once per instance: /users/1 → /users/2 keeps user 1    const id = this.route.snapshot.paramMap.get('id');    this.http      .get<User>(`/api/users/${id}`)      .subscribe((u) => this.user.set(u));  }}

In the right version nothing depends on when the component was created. httpResource() reads this.id(), so it sends a new request whenever the id changes and cancels the one still in flight, which also means a fast double click can't leave user 1's response on user 2's page. Anything else derived from the id, a computed() title or a linkedSignal() tab, updates the same way.

If you can't enable input binding, the same idea works with ActivatedRoute: turn route.paramMap.pipe(map((p) => p.get('id'))) into a signal with toSignal(), or pipe it into an operator that handles the request. Which flattening operator you choose there matters, and switchMap is right for this kind of read.

On /users/1 → /users/2Runs again?
Constructor and field initializersNo
ngOnInitNo
A value read once from route.snapshotNo, it keeps the old id
paramMap, params and data ObservablesYes, they emit the new values
Inputs bound by withComponentInputBinding()Yes, they're updated
Guards and resolversYes, by default, for path and matrix params

How to apply it in your project

  1. Find one-time route readsSearch components for snapshot.paramMap, snapshot.params, snapshot.queryParams and snapshot.data. Each one in a route that can link to itself is a stale-data bug waiting for the right click.
  2. Turn route values into inputsAdd withComponentInputBinding() to provideRouter(), declare input()s named after the parameters, and derive requests and titles from them with httpResource() and computed().
  3. Reset state that belongs to one entityList what the page keeps locally, such as tabs, drafts, selections and pagination, and reset each item when the id changes, with a linkedSignal() sourced from the id or an explicit reset.
  4. Test detail-to-detail navigationAdd an end-to-end test that goes from one detail page to another through a link and asserts that the heading and the requests changed.

Key takeaways

  • The default BaseRouteReuseStrategy keeps the component when the route config matches and only params change.
  • The constructor and ngOnInit run once per instance, so an id read from route.snapshot there goes stale.
  • Local state survives reuse too; reset what belongs to one entity when the id changes.
  • Read route values as signals, with withComponentInputBinding() or toSignal(route.paramMap), and derive the rest.

📚 المصادر

  1. BaseRouteReuseStrategy — Angular
  2. Read route state — Angular
  3. withComponentInputBinding — Angular
  4. RunGuardsAndResolvers — Angular
  5. Reactive data fetching with httpResource — Angular

التعليقات (0)