angularangular-standalone-componentsbarrel-import

How to use angular component when using barrels module (shared module)


I'd like to migrate my project to use standalone component.

But I'm using quite a lot of "Barrel imports" What's a barrel?

So, I just

  1. added the following to my component
@Component({
  standalone: true,
  // ...
})
export class SharedComponent { 
 //... 
}
  1. Removed the shared-component.module.ts file
  2. Replace the "export" section in my barrel module
// shared.module.ts
@NgModule({
  exports: [
    // Shared
    SharedFormsModule,

    // Modals
    SharedComponent, // <-- Error (1)
    // ...

I do get the following error

Error (1)

Can't be exported from this NgModule, as it must be imported first

So tried to declare it first

// shared.module.ts
@NgModule({
  declarations: [ModalDeleteArchiveComponent], // <-- Error (2)
  exports: [
    // Shared
    SharedFormsModule,

    // Modals
    SharedComponent, // <-- Error (1)
    // ...

But now I do get

Error (2)

Component ModalDeleteArchiveComponent is standalone, and cannot be declared in an NgModule. Did you mean to import it instead?

Somebody knows how to make this work?


Solution

  • standalone components should be listed in imports, not in declarations.

    // shared.module.ts
    @NgModule({
      declarations: [ModalDeleteArchiveComponent], // <-- Wrong
      imports: [ModalDeleteArchiveComponent], // <-- Correct
      exports: [
        // Shared
        SharedFormsModule,
    
        // Modals
        SharedComponent,
        // ...
      ]