Sekrab Garage

Angular standalone provideRouter

Angular standalone router providers: an update

AngularTip October 31, 22
Subscribe to Sekrab Parts newsletter.
Series:

Standalone

In this article, we will turn some components in an existing Angular app into standalone components, to see if this feature is worth the trouble. What else do they need to work properly? What scenarios are they best used for? How do they affect development experience? and Output bundles?
  1. two years ago
    How to turn an Angular app into standalone - Part I
  2. two years ago
    How to turn an Angular app into standalone - Part II
  3. two years ago
    Angular standalone router providers: an update
  4. two years ago
    Angular 15 standalone HTTPClient provider: Another update
  5. 12 months ago
    Angular Standalone in SSR: update

Since standalone is still in preview, the documentation gives you no hints. You have to excavate to find some. On medium, Andrew Scott blogged about advancements made by Angular team on the router, when in standalone.

anchorReplacing the RouterModule

In our previous attempt to tear down the AppModule, the main.ts was rewritten

// main.ts bootstrap passing all providers from an existing NgModule
// using importProvidersFrom
bootstrapApplication(AppComponent, {
  providers: [
    importProvidersFrom(RouterModule.forRoot(AppRoutes)),
  ],
});

The new proposed way is to use provideRouter

// new way with provideRouter in main.ts
bootstrapApplication(AppComponent, {
  providers: [
    provideRouter(appRoutes),
  ]
});

anchorRewriting our App Routes with options

Let's revisit our app.route in StackBlitz project and rewrite it.

// app.route rewriting the router providers using provideRouter
export const AppRouteProviders = [
  provideRouter(AppRoutes,
    // this is in place of scrollPositionRestoration: 'disabled',
    withInMemoryScrolling({
      scrollPositionRestoration: 'disabled',
    }),
    // in place of initialNavigation: 'enabledBlocking'
    withEnabledBlockingInitialNavigation(),
    // same configuration
    withRouterConfig({
      paramsInheritanceStrategy: 'always',
      onSameUrlNavigation: 'reload'
    }),
    // in place of  preloadingStrategy: PreloadService,
    withPreloading(PreloadService),
  ),
  // ...
];

anchorBundle sizes

The article claims that when not using the sub features of the router, tree shaking should result in reduction in bundle size. I could not reproduce that. As a matter of fact, the provideRouter almost always generated a slightly larger main bundle. The lazy loaded and common bundles were not affected.

Donno. You be the judge.

  1. two years ago
    How to turn an Angular app into standalone - Part I
  2. two years ago
    How to turn an Angular app into standalone - Part II
  3. two years ago
    Angular standalone router providers: an update
  4. two years ago
    Angular 15 standalone HTTPClient provider: Another update
  5. 12 months ago
    Angular Standalone in SSR: update