简体   繁体   中英

Library Routing in Angular 14 with Standalone Components

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.

Just drop the.forChild([]). You don't want a "ModuleWithProviders" at your component level.

If I'm not mistaken, since version 14.2

You can use routing like this:

export const TEST_ROUTES: Routes = [
  {
    path: '',
    redirectTo: 'test1',
    pathMatch: 'full',
  },
  {
    path: '',
    component: TestComponent,
    children: [
      {
        path: 'test1',
        loadComponent: () =>
          import('../test1/test1.component').then((m) => m.Test1Component),
      },
    ],
  },
];

then

export const APP_ROUTES: Routes = [
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'test',
  },
  {
    path: 'test',
    loadChildren: () =>
      import('./app/test/test.routes').then((m) => m.TEST_ROUTES),
  },
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM