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

What steps are needed to have typescript recognize a typed function as a throw-statement?

I'm grappling with a typescript issue - I have a custom function that consistently throws an error, which is used to handle null variables. Strangely, if I directly throw an error without using the function, typescript recognizes that the variable can ...

When I apply both `*ngIf` and `*ngFor` to the same element, why does `*ngFor` insert a null item into the array that I am iterating over?

Custom Design, Visualization. Switching from the *ngIf directive to the [hidden] property greatly improves the appearance and eliminates any null items. ...

While developing an exam portal with Angular and Spring Boot, I encountered an issue when trying to incorporate a name field as [name]

Component.html <div class="bootstrap-wrapper" *ngIf="!isSubmit"> <div class="container-fluid"> <div class="row"> <div class="col-md-2"> <!- ...

Is there a way to eliminate the line that appears during TypeScript compilation of a RequireJS module which reads: Object.defineProperty(exports, "__esModule", { value: true });?

Here is the structure of my tsconfig.json file: { "compileOnSave": true, "compilerOptions": { "module": "amd", "noImplicitAny": false, "removeComments": false, "preserveConstEnums": true, "strictNullChecks": ...

In Angular, use the ngFor directive to iterate through items in a collection and add a character to each item except

Currently, I am iterating through my data list and displaying it in the view using spans: <span *ngFor="let d of myData"> {{d.name}}, </span> As shown above, I am adding a comma ',' at the end of each item to ensure a coherent displ ...

I've noticed that tailwindcss is causing issues with some of the styles in my angular project

Recently, I integrated tailwindcss 2.0.4 into my angular 11.2.6 project. After completing the installation and adding necessary imports, the appearance of the page had changed. Take this button for instance: Prior to integrating tailwindcss, the button ...

Creating dynamic components in Angular 2 and adding them to the view container of the body

I've been grappling with the challenge of dynamically generating a component and then adding it to the document tag. My struggle lies in figuring out the proper method for selecting the body's ViewContainerRef so that I can easily append a new co ...

What is a superior option to converting to a promise?

Imagine I am creating a function like the one below: async function foo(axe: Axe): Promise<Sword> { // ... } This function is designed to be utilized in this manner: async function bar() { // acquire an axe somehow ... const sword = await foo ...

Issue encountered while utilizing combineReducers: "Error: The assetsReducer returned an undefined value during initialization."

Issue: The "assetsReducer" has returned an undefined value during initialization. When the state passed to the reducer is undefined, it must explicitly return the initial state, which cannot be undefined. If no value is set for this reducer, consider using ...

Exploring Vue 3: Crafting a custom plugin using the composition API and enhancing it with Typescript type augmentation

Encountering an issue with displaying plugins properly within <script> and <template> tags on WebStorm. Firstly, let's take a look at my files and configuration: tsconfig.config.json { "extends": "@vue/tsconfig/tsconfig. ...

Encountering an issue while attempting to start ng serve due to the error message stating "Module '@angular/compiler-cli' cannot be located"

I am facing an issue with running my Angular project. Whenever I try to execute ng serve, it fails with the following error: dev@716a5115c45c:~/project$ npx ng serve Cannot find module '@angular/compiler-cli' Error: Cannot find module '@ang ...

Assign an appropriate label to this sonarqube input field

Sonarqube flagged an issue with the following line of code: <div class="dropdown-language"> <label>{{'GENERALE.LINGUA' | translate }}</label> <select #langSelect (change)="translate.use(langSe ...

What is the best way to iterate through a list of values stored in a form group's array?

I am facing an issue with my form group declaration. Below is the code snippet: this.secondFormGroup = this._formBuilder.group({ nested: this._formBuilder.group({ arr1: [], arr2: [], arr3: [], arr4: [] }), }) After the user fi ...

How can I create an input field in MUI that restricts input to letters, numbers, and dashes

Is there a way to configure an MUI input field so that it only accepts letters, numbers, and dashes while excluding spaces and symbols such as (*&^%$#@!,.<>{}[])? Specifically, I want to allow characters that wouldn't disrupt a URL, like . Tha ...

Trying to filter an array of number|undefined in TypeScript to only include numbers is not identified as an array of numbers

Below is the code snippet: type TEntity = Array<{ size?: number }> const someVar: TEntity = //@ts-ignore getFromSomewhere() function isNumber(input: any): input is number { return !isNaN(Number(input)) } const sizes1: number[] = so ...

Tips for changing a created Word file with Docxtemplater into a PDF format

Hey there! I am currently in the process of building a website with Angular.js and have successfully managed to generate a word document from user input. Everything was working fine until I encountered an issue. I now need to provide a way for users to pr ...

Resolving the Angular5 (Angular Universal) problem with page source visibility

Currently tackling a server-side rendering project, inspired by the Angular Universal guide. Everything seems to be on track, but I'm facing an issue where even when navigating to different routes, the source code for the initial page is displayed whe ...

Navigating the onSubmit with Formik in React: Tips and Tricks

I have a query regarding my usage of Formik in my React application. Within the onSubmit function, I am making an API call to a service. If this call fails, I want to immediately stop the rest of the submission process without executing any further action ...

Tips for configuring the global API baseUrl for useFetch in Nuxt 3

Is there a way to globally set the baseUrl used in the useFetch composable, possibly through nuxt.config.ts? How can I prevent having to specify it in each individual useFetch call? ...

How to retrieve a stored value using Ionic 3 native storage

Hey there, I recently attempted to implement code from the Native Storage plugin documentation found at this link: Native Storage import { NativeStorage } from '@ionic-native/native-storage'; constructor(private nativeStorage: NativeStorag ...