angularangular-clinode-modulesangular-components

How do I create an angular component as part of a library and use it in my application


So I have the following situation

  1. I have created an angular library ng generate library my-lib
  2. I have added a simple component using Ng generate component .lib/test which creates a standalone component like so
import { Component } from '@angular/core';

@Component({
  selector: 'lib-test',
  standalone: true,
  imports: [],
  templateUrl: './test.component.html',
  styleUrl: './test.component.css'
})
export class TestComponent {

}
  1. I then pack up my application by running ng build then cd ../../dist/my-lib && npm pack
  2. I go to my main application and run npm install {pointTofolder}/dist/my-lib/my-lib-0.0.1.tgz
  3. I go to use in my application and I get the following error

'lib-test' is not a known element:

  1. If 'lib-test' is an Angular component, then verify that it is part of this module.
  2. If 'lib-test' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

What am I missing / doing wrong? It's the most simple example of using a component in a library


Solution

  • I used these two links

    1. Standalone component NG8001: 'component' is not a known element
    2. https://stackoverflow.com/a/65740167/2987066

    And this lead me to the following:

    1. Make sure the route is importing the module the Import's and Export's of that module

       const routes: Routes = [
      {
       path: '',
       component: MyComponent,
       children: [
         {
           path: '',
           loadChildren: () => import('./routes/my/my.module').then(m => m.MyModule)
         },
       ]
      }];
      

    Then make sure that the component you want to load is in both the imports and the exports of the module you just loaded above (for standalone componets)

    @NgModule({
      imports: [
        CommonModule,
        FormsModule,
        ReactiveFormsModule,
        RouterModule,
        TestComponent
      ],
        declarations: [
    
      ],
      exports: [
        CommonModule,
        FormsModule,
        ReactiveFormsModule,
        RouterModule,
        TestComponent
      ]
    })
    

    If your component is not a Standalone component, you can do the same thing but import it through a module

      imports: [
        CommonModule,
        FormsModule,
        ReactiveFormsModule,
        RouterModule,
        CommonUiModule
      ],
        declarations: [
      ],
      exports: [
        CommonModule,
        FormsModule,
        ReactiveFormsModule,
        RouterModule,
        CommonUiModule
      ]
    

    And in this case CommonUiModule looks like the following

    @NgModule({
      imports: [
      ],
      declarations: [
        TestComponent
      ],
      exports: [
        TestComponent
      ]