Search code examples
angularangular-library

Angular routing and importing components from a library


I have set up a simple skeleton representing my application here: https://stackblitz.com/edit/angular-e68rbx

The app module loads and hands off to a framework module which hosts the main pages in my app.

To demonstrate the problem I have put 1 of my component library buttons in each of the framework and test-page components but no matter what I try I cannot get the button in the test-page to render as a button from my library.

If I import the ButtonModule in the app.module.ts then neither button is rendered correctly.

If I import the ButtonModule in the framework.module.ts then the button in the framework page is rendered correctly, but the button in the test-page is not.

What is the correct way to get a library module working throughout an Angular app?


Solution

  • Your TestPageComponent needs to be declared anywhere. So if you don't wanna do it in the App.Module.ts so you need to to this in the Framework.Module. With lazy loading it helps for better performance. So change your framework.module.ts like this:

    import { CommonModule } from '@angular/common';
    import { RouterModule } from '@angular/router';
    import { FrameworkComponent } from './framework.component';
    import { FrameworkRoutingModule } from './framework.routing.module';
    import { ButtonModule } from 'jon-component';
    import { TestPageComponent } from '../components/test-page/test-page.component';
    
    @NgModule({
      declarations: [FrameworkComponent, TestPageComponent],
      imports: [FrameworkRoutingModule, CommonModule, ButtonModule],
      exports: [FrameworkComponent, RouterModule],
    })
    export class FrameworkModule {}
    

    You see the TestPageComponent in the line declarations: [FrameworkComponent, TestPageComponent], does the trick.

    enter image description here