If I have a very simple component that is part of an Angular component library, it might look like this:
mycomponent.module.html
<div>
<a routerLink="/">
</div>
mycomponent.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: './mycomponent.component.html'
})
export class MyComponentComponent implements OnInit {
@Input() title: string;
constructor() { }
ngOnInit() {
}
}
mycomponent.module.ts
import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponentComponent} from './mycomponent.component';
@NgModule({
declarations: [MyComponentComponent],
imports: [
CommonModule,
RouterModule
],
exports: [MyComponentComponent]
})
export class MyComponentModule{ }
After publishing this library, I use this component in another project by importing MyComponentModule like this:
myproject.module.ts
@NgModule({
imports: [CommonModule, RouterModule, MyComponentModule],
declarations: []
})
export class MyProjectModule{}
Then, I encounter the following stacktrace:
ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[RouterLinkWithHref -> Router]:
StaticInjectorError(Platform: core)[RouterLinkWithHref -> Router]:
NullInjectorError: No provider for Router!
NullInjectorError: StaticInjectorError(AppModule)[RouterLinkWithHref -> Router]:
StaticInjectorError(Platform: core)[RouterLinkWithHref -> Router]:
NullInjectorError: No provider for Router!
at NullInjector.get (vendor.js:131635)
at resolveToken (vendor.js:146553)
at tryResolveToken (vendor.js:146479)
at StaticInjector.get (vendor.js:146329)
Even though MyProjectModule includes RouterModule and functions correctly when using
<a routerLink="/"></a>
, it fails when the routerLink is within a child component from an external library. Navigation works everywhere else in the application. What could be causing this issue?