16 Nov 2026
7 min

withAutoCleanupInjectors – a game changer for route providers

Route-level providers in Angular live longer than the page that uses them – and since version 22.2 there is a stable cure for that: withAutoCleanupInjectors().

A common problem: where does stale data in the table come from after a route change?

Sound familiar? You have a /users view with a table of users. You keep the list state in a service (store) that you provide in the route configuration, so as not to clutter the root. You open the list, the data loads. You go to /dashboard. You come back to /users.

And for a split second you see the old list. Only then does the API response arrive and the table gets replaced. Sometimes it's just a flicker, sometimes the user manages to click a row that no longer exists.

This is one of the most common problems in applications that keep state in route providers – and it is not a bug in your component. It is a consequence of how the router manages route injectors.

Why this happens

When you add providers to a Route object, the router creates a separate EnvironmentInjector for that route. It is created on the first visit to the route and from then on it is kept together with the route's configuration.

The component and the route injector have different lifecycles:

  • The component is destroyed when you leave the route (unless RouteReuseStrategy stores it).
  • The route injector is not destroyed at all by default. The services in it live until the end of the application's lifetime, and their ngOnDestroy is never called.

So after you return to /users, the new component injects the same old store. The store still holds the previous list in its signal, so the table renders it immediately, and the fresh request arrives a moment later.

The side effects go beyond a data flicker: subscriptions with takeUntilDestroyed() in such a service never complete, DestroyRef.onDestroy never fires, and memory grows with every subsequent visited route that has providers.

Typical workarounds, i.e. state-clearing tricks

Until now, state had to be cleared manually. The most popular pattern is a reset() method in the store, called when the component is destroyed:

users.state.ts
reset(): void {
  this.users.set([]);
}
users.ts
export class Users implements OnDestroy {
  protected state = inject(UsersState);

  constructor() {
    this.state.loadUsers();
  }

  ngOnDestroy(): void {
    this.state.reset(); // manual state clearing
  }
}

Other variants you come across:

  • clearing the state at the beginning of loadUsers() (this.users.set([]) before the request),
  • inject(DestroyRef).onDestroy(() => this.state.reset()) in the component instead of ngOnDestroy,
  • moving UsersState to the component's providers, which, however, cuts it off from the child routes that were supposed to share it.

They all have the same drawbacks:

  • Boilerplate. The same pattern – a reset() method in the service plus ngOnDestroy or DestroyRef in the component – has to be repeated for every view with state in route providers. A dozen or so routes means a dozen or so copies of the same code.
  • Easy to forget. Every new store and every new component that uses it is another place for reset(); one oversight and the flicker is back.
  • The reset has to know the whole state. You add a field to the store and you have to remember to add it to reset().
  • It treats the symptom, not the cause. The service is still alive: its subscriptions, timers and takeUntilDestroyed() are still not cleaned up, and the memory is not released.
  • The component manages the service's lifecycle. Angular creates the services, so it should also destroy them. With a manual reset, the component has to keep track of when to clear the service's state, even though that shouldn't be its concern.

Reproducing the problem

The sample project has two pages: Dashboard and Users. The user list is generated by @ngneat/falso, and delay(3000) simulates a slow API so that the effect is clearly visible.

features/users/users.state.ts
@Injectable()
export class UsersState {
  private userService = inject(UserService);
  private destroyRef = inject(DestroyRef);

  users = signal<User[]>([]);

  loadUsers(): void {
    const users$: Observable<User[]> = this.userService.getUsers();

    users$
      .pipe(delay(3000), takeUntilDestroyed(this.destroyRef))
      .subscribe((result) => {
        this.users.set(result);
      });
  }
}
app.routes.ts
export const routes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
  { path: 'dashboard', component: Dashboard },
  {
    path: 'users',
    providers: [UsersState],
    component: Users,
  },
];
features/users/users.ts
@Component({
  selector: 'app-users',
  templateUrl: './users.html',
})
export class Users {
  protected state = inject(UsersState);

  constructor() {
    this.state.loadUsers();
  }
}
features/users/users.html (fragment)
@for (user of state.users(); track user.id) {
  <tr>
    <td>{{ user.id }}</td>
    <td>{{ user.name }}</td>
    <td>{{ user.email }}</td>
  </tr>
}

The effect is easiest to see by going through /users → /dashboard → /users in sequence. On the second visit, the table immediately shows the ten users from the previous visit, and after 3 seconds replaces them with a new, random ten. The Users component is new, but UsersState is still the same instance, so the users signal holds the old list.

The solution: withAutoCleanupInjectors()

Instead of a manual reset in every component, a single line in the router configuration is enough. The routes and the store stay unchanged, and the reset() methods and the cleanup in the component's ngOnDestroy can simply be removed.

app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter, withAutoCleanupInjectors } from '@angular/router';

import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(routes, withAutoCleanupInjectors()),
  ],
};

The example described above runs on Angular 22.2.3 (currently the latest stable version) and already uses the stable withAutoCleanupInjectors(). If your project is on a version earlier than 22.2, the same option is called withExperimentalAutoCleanupInjectors() – after upgrading, you only need to change the name in the import and in provideRouter.

After every completed navigation, the router checks which route injectors are no longer in use – neither by active routes nor by routes stored by RouteReuseStrategy – and destroys them.

To see this, add a log to UsersState in the constructor and in ngOnDestroy. The /users → /dashboard → /users path now produces this in the console:

UsersState created
UsersState destroyed   // leaving for /dashboard
UsersState created     // back to /users – new instance, empty list

On return, the table is empty for 3 seconds and then shows the new list – without data from the previous visit and without any reset().

Behavior Default With withAutoCleanupInjectors()
Component destroyed after leaving the route yes yes
Route injector destroyed after leaving no yes
ngOnDestroy / DestroyRef in the route service never when the injector is destroyed
Service state after returning to the route old fresh instance

What to watch out for

Same route configuration = same injector. Navigating from /users/1 to /users/2 does not destroy the store, because both paths are one Route object that is still active. If the state depends on a parameter, you still have to reset it yourself (e.g. in an effect on an input() holding the parameter).

Custom RouteReuseStrategy. The feature is opt-in and requires shouldDestroyInjector(route) to return true for the routes to be cleaned up. With the default strategy or one extending BaseRouteReuseStrategy, this behavior is already provided. If your strategy stores routes (store / retrieve), also implement retrieveStoredRouteHandles() – otherwise the router doesn't know that a stored component still needs its injector.

export class KeepUsersStrategy extends BaseRouteReuseStrategy {
  private readonly handles = new Map<string, DetachedRouteHandle>();

  override shouldDetach(route: ActivatedRouteSnapshot) {
    return route.routeConfig?.path === 'users';
  }
  override store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null) {
    const key = route.routeConfig!.path!;
    handle ? this.handles.set(key, handle) : this.handles.delete(key);
  }
  override shouldAttach(route: ActivatedRouteSnapshot) {
    return this.handles.has(route.routeConfig?.path ?? '');
  }
  override retrieve(route: ActivatedRouteSnapshot) {
    return this.handles.get(route.routeConfig?.path ?? '') ?? null;
  }
  // crucial with withAutoCleanupInjectors:
  override retrieveStoredRouteHandles() {
    return [...this.handles.values()];
  }
}

Root vs route. Cleanup applies only to route injectors. A service with providedIn: 'root' (not registered in the route's providers) keeps living and will still show stale data after you return.

Intentional caching stops working. If someone found it convenient that the list was “remembered” between visits, that effect disappears once the feature is enabled. Move such state deliberately to the root or to the reuse strategy.

When to enable it and where it came from

The feature appeared in Angular 21.1 as withExperimentalAutoCleanupInjectors(), and since 22.2 it has been stable under the name withAutoCleanupInjectors().

Enable it if:

  • you keep view state (store, filters, pagination) in route providers,
  • route services have subscriptions, timers or WebSockets that should be closed,
  • you want takeUntilDestroyed() and DestroyRef in those services to work the way you expect.

Be careful if the application intentionally relies on route data staying in memory after you leave the route, e.g. the list should appear immediately after returning, without reloading. After you enable withAutoCleanupInjectors(), that data will disappear, so first move it to a service with providedIn: 'root'.

Summary

Route providers have always promised “state tied to the view”, but without cleanup it was state tied to the application. withAutoCleanupInjectors() makes good on that promise: you leave the route, its services die, and when you come back you start with a clean slate – no flickering stale data in the table.

Share this post

Sign up for our newsletter

Stay up-to-date with the trends and be a part of a thriving community.