Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import components as array in Angular standalone components

Tags:

angular

I created a library using standalone components. In this library, I export related components in arrays like this:

export const TABLE_COMPONENTS: Type<any>[] = [
  TableComponent,
  TableHeaderComponent,
  TableBodyRowDirective,
  TableHeaderRowDirective,
  TableBodyEmptyRowDirective,
  TableFooterRowDirective,
  TableFirstRowDirective,
  TableFilterIconDirective,
  TableLastRowDirective
];

But when I try to use this array in the consuming application it does not work. I tried like this:

imports: [
    TABLE_COMPONENTS
],

But I get the error "'imports' must be an array of components, directives, pipes, or NgModules. Value is a reference to 'TABLE_COMPONENTS'". I also tried:

  • Using the spread operator to "flatten" the array
  • Exporting components as Provider[] or any[]
  • Exporting components without specifying the type of the array

I even tried using the same syntax as in the official Angular guide

export const TABLE_COMPONENTS = [
  TableComponent,
  TableHeaderComponent,
  TableBodyRowDirective,
  TableHeaderRowDirective,
  TableBodyEmptyRowDirective,
  TableFooterRowDirective,
  TableFirstRowDirective,
  TableFilterIconDirective,
  TableLastRowDirective
] as const;

The weird thing with this syntax is that vscode does not complain, but then, I get the error above during the compilation.

Does anyone know how to export related components into an array in order to import them at once instead of one by one?

Updated:

One important thing I forgot to mention is that I have a playground application for this library that references it directly (so not via a npm link or by installing the package) and there, it works. The issue seems to appear when I consume the library from a different application where I install it.

like image 569
ssougnez Avatar asked Mar 20 '26 23:03

ssougnez


1 Answers

The problem is that you're making a 2-dimensional array the way you have it set up.

export const TABLE_COMPONENTS: Type<any>[] = [
  TableComponent,
  TableHeaderComponent,
  TableBodyRowDirective,
  TableHeaderRowDirective,
  TableBodyEmptyRowDirective,
  TableFooterRowDirective,
  TableFirstRowDirective,
  TableFilterIconDirective,
  TableLastRowDirective
];


imports: [
    TABLE_COMPONENTS
],

After this, your imports will be an array with 1 element, which is itself an array. If you use the spread operator, it should work as you intend:

imports: [
    ...TABLE_COMPONENTS
]

You may also need to remove the Type<any>[] typing from the TABLE_COMPONENTS to coerce it

Here's a working StackBlitz example showing it working as expected with no typing, and using the spread operator: StackBlitz Example

like image 101
Cineris Avatar answered Mar 22 '26 14:03

Cineris