ssougnez
ssougnez

Reputation: 5886

Import components as array in Angular standalone components

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:

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.

Upvotes: 3

Views: 4533

Answers (2)

adem1414
adem1414

Reputation: 1

What works for me was not making a 2-dimensional array, but directly put in each component "imports" the dependencies as array:

@Component({
......
imports:[TableComponent,TableHeaderComponent,TableBodyRowDirective,...etc]

Upvotes: 0

Cineris
Cineris

Reputation: 581

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

Upvotes: 1

Related Questions