Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Library Routing in Angular 14 with Standalone Components

Tags:

angular

I'm using Angular 14 and their new Standalone Components feature in the context of a library. How can I use RouterModule.forChild() in the component as Angular won't let me do it?

...
projects/
  my-lib/
    src/lib
      root.component.ts
  my-app/
...
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { RouterModule } from '@angular/router';

@Component({
  standalone: true,
  imports: [CommonModule, RouterModule.forChild([])],
  selector: 'my-lib-root',
  template: ` <router-outlet></router-outlet>`,
})
export class RootComponent {}

Got the error

'imports' contains a ModuleWithProviders value, likely the result of a 'Module.forRoot()'-style call. These calls are not used to configure components and are not valid in standalone component imports - consider importing them in the application bootstrap instead.

But as I'm using a library, I don't have any "application bootstrap" in this context.

like image 762
GreatHawkeye Avatar asked Oct 23 '25 15:10

GreatHawkeye


1 Answers

If you need all, or multiple RouterModule directives in your standalone component, you can import them all by importing the whole RouterModule.

@Component({
  standalone: true,
  imports: [CommonModule, RouterModule],
  ...
})
export class MyAwesomeComponent {}

The preferred way would be importing only the directives you will actually use. For example, if you plan to use 'router-outlet' from RouterModule, you can just import RouterOutlet.
The same applies for all the other components, directives, or whole modules.

@Component({
  standalone: true,
  imports: [CommonModule, RouterOutlet],
  ...
})
export class MyAwesomeComponent {}
like image 127
PaxForce Avatar answered Oct 26 '25 07:10

PaxForce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!