RouterModule is a crucial external component that is essential for integrating

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?

Answer №1

After some time, I managed to find the answer.

Avoid using an external library with paths in tsconfig.json if it requires service injection (e.g. routing).

The external library that included MyComponentModule was forcedly added through the paths object in tsconfig.json, for example:

"paths": {
  "my-library": ["../my-library/lib/src/"]
}

Although this simplified development by enabling hot reloading when making changes to the library, it interferes with proper module injections.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing the [mat-dialog-close] directive within an Angular dialog component

While attempting to utilize the suggested code in the dialog template for opening a dialog component to either confirm or cancel an action, I encountered an error with the following message. Why did this happen? Property mat-dialog-close is not provided by ...

Leveraging a traditional npm package within an Angular or Ionic project

I am interested in how to access a .plist file within an Angular / Ionic application. After discovering the npm module at this link: https://www.npmjs.com/package/plist I have successfully added it to my project, but I am now considering the most effecti ...

Tips for receiving @ mentions in PrimeNg Editor using Quill and quill-mention with Angular

Currently, I have been given the task of adding a mentions feature to our text editors. The editor I am working with is the PrimeNg Editor, built on Quill. After some research, I came across the package quill-mention, which appears to be a potential soluti ...

Utilizing the FormsModule and ReactiveFormsModule within a Component module

I am facing an issue with integrating a reactive form into a generated component called boom-covers. I am utilizing the [formGroup] property as shown below: <form name="boomCovers" method="post" id="bomCovers" (ngSubmit)=&q ...

How can a TypeScript object be declared with a single value assignment to itself?

Whenever I try to declare an object and assign a key to itself, I encounter errors. I have attempted different methods, but the error persists. const a = { d:123, a:a//<-TS2448: Block-scoped variable 'a' used before its declaration. } co ...

Troubleshooting Angular 2: Why Array Interpolation is Failing

Greetings everyone, I am diving into Angular 2 and attempting to create a basic Todo application. Unfortunately, I've hit a roadblock. My array interpolation seems to be malfunctioning. Any assistance would be greatly appreciated. Here is my AppCompo ...

Creating a cucumber feature file from an Excel sheet or any other type of file: A step-by

I currently have an excel sheet containing various scenarios that I need to convert into a feature file. Can you assist me in accomplishing this task? Do you know of any plugins that can help streamline this process? Any guidance would be greatly apprecia ...

Angular: Real-time monitoring of changes in the attribute value of a modal dialog and applying or removing a class to the element

I cannot seem to figure out a solution for the following issue: I have two sibling div elements. The second one contains a button that triggers a modal dialog with a dark overlay. However, in my case, the first div appears on top of the modal dialog due to ...

What could be causing my TestBed providers to not properly replace the actual service in use?

Currently, I am attempting to test a basic component that relies on a dependency. My objective is to mock this dependency, but despite my efforts, the real service is still being initialized. Can anyone identify what I might be overlooking? Below is the c ...

Sending an array of strings to the function is not allowed

I'm encountering an issue with the following function: function proc(unames: Array<string>){} When I attempt to pass the function the following input: import _ = require('lodash'); const usernames = _.flattenDeep([unames]).filt ...

Using *ngIf to verify the presence of an attribute

Currently working with Angular2 and trying to implement a condition to display something. For instance, if group.permissions=Can Create File, then something should appear on the page. This is the code I have written so far: <div class="col-md-9" *ngI ...

Zendesk API integration with Angular is experiencing issues with retrieving data as a result of a CORS restriction

I have been working with the Zendesk API and have encountered a problem. Despite being able to successfully send POST requests (even though the response indicates an error), I am unable to make GET requests using my Angular 4 application along with HttpCli ...

Ways to encourage children to adopt a specific trait

Let's discuss a scenario where I have a React functional component like this: const Test = (props: { children: React.ReactElement<{ slot: "content" }> }) => { return <></> } When a child is passed without a sl ...

What is the best way to display a custom row overlay in ag-grid?

I am looking to display a customized message when no users are found using ag-grid in Angular6. Below is the code snippet: ngOnInit() { this.gridOptions.frameworkComponents.loadingCellRenderer = TableLoadingComponent; this.rowBuffer = 0; this.rowSel ...

In TypeScript, is it possible to indicate that a function will explicitly define a variable?

In TypeScript, I am working on creating a class that delays the computation of its information until it is first requested, and then caches it for future use. The basic logic can be summarized as follows. let foo: string | undefined = undefined; function d ...

Struggling with sluggish performance on a certain project within VS Code

My experience with VS code has been excellent over the years, but I recently encountered a problem in one of my projects that caused a significant slowdown in performance. Strangely, other projects are working fine without any issues on VS code. I suspect ...

Is it feasible to use Angular2 in conjunction with ui-calendar?

Entering the fascinating world of Angular 2 has me feeling like a beginner again. My team and I had been utilizing angularjs with ui-calendar in our project, but now we're transitioning to Angular 2 due to new production requirements. The challenge ar ...

The malfunctioning collapse feature in Bootstrap 4 sidebar within an Angular 6 application

I am trying to find a way to collapse and reopen the sidebar when clicking on a button. I have attempted to create a function to achieve this, but unfortunately it did not work as expected. Important: I need to collapse the sidebar without relying on jque ...

Tips for troubleshooting compile errors when updating an Angular project from version 6 to 7

I am currently working on upgrading my Angular 6 project to Angular 10, following the recommended approach of going through one major version at a time. Right now, I am in the process of updating it to version 7.3. Despite following the steps provided on u ...

Issue: The canActivateChild method in the child guard is not functioning as

Following the Angular documentation, I attempted to implement a child guard in my code: @Injectable() export class AuthGuardService implements CanActivate, CanActivateChild { constructor(private authService: AuthentificationService, private router: Rou ...