1

I'm using standalone components in my Angular 15 app, and I'm realizing that 4-5 of them are going to be useful across projects, so I considered moving them into an npm library. Everything I know about libraries though is that they're done via modules. Is there something special that needs to be done for standalone, or is it just "You don't use standalone in a library"?

I tried to just put the standalone components there without any module file, and then I exported the components. It compiles file, but when I run I get a ton of errors saying:

G0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with EnvironmentInjector#runInContext.

Those errors don't exist before pulling the components out.

In my library component I've done this:

export const PERSON_DEFAULT_OPTIONS = new InjectionToken<IPersonDefaults>('Graph Toolkit person defaults')

export interface IPersonDefault { ... }

@Component({...})
export class PersonComponent {
    readonly #config = inject(PERSON_DEFAULT_OPTIONS, {optional: true})
}

That seems to be what's triggering the error. I also tried the "old" syntax:

constructor(@Optional() @Inject(PERSON_DEFAULT_OPTIONS) ...

The app that calls the library provides that token in main.ts

Gargoyle
  • 9,590
  • 16
  • 80
  • 145
  • This is thoroughly covered in the docs https://angular.io/guide/creating-libraries Is there something not covered there that you still have a question about? – Mark Clark Mar 06 '23 at 17:41
  • @MarkClark I don't see anything in the angular guide related to standalone components in a library. – Gargoyle Mar 06 '23 at 18:45
  • I believe standalone components in libraries aren't different from the ones in application. could you provide a piece of code where `inject()` is used inside of a component? – Andrei Mar 06 '23 at 19:59
  • @Andrei I added to the question description. – Gargoyle Mar 06 '23 at 20:16
  • What is standalone component???? – Antoniossss Mar 06 '23 at 20:20
  • @Antoniossss Was introduced in NG14 and omits the writing of an angular module – Pieterjan Mar 06 '23 at 20:33
  • According to [this link](https://angular.io/guide/standalone-components#using-standalone-components-in-ngmodule-based-applications) all should be possible and the system is designed to incrementally migrate from `NgModule` applications to standalone module applications seamlessly. So I guess combining both principles should be possible, and thus libraries of both kinds should be able to be used in applications of both kinds – Pieterjan Mar 06 '23 at 20:40
  • hm, and could you please also add a piece of code where this component gets to the application? is it just imported into some module's imports? or maybe rendered dynamically? – Andrei Mar 06 '23 at 20:54
  • @Andrei There are no modules. It's just put into the import of the app's `@Component{}` specifier. – Gargoyle Mar 06 '23 at 21:44

0 Answers0