steps for creating a route with @input

I have created a component that utilizes an HTML attribute. I set it up so that users can specify the route when using this component within another component. However, every time I attempt to define the route value, I encounter a 'No provider for Router' error.

When viewing the browser, I see the following output:

ERROR Error: StaticInjectorError(AppModule)[RouterLinkActive -> Router]: StaticInjectorError(Platform: core)[RouterLinkActive -> Router]: NullInjectorError: No provider for Router!

Below is the code snippet for the component :

@Component({
  selector: 'li[o-nav-link]',
  template: `
    <a #link [routerLink]="route" class="nav-link" routerLinkActive="active"
     [attr.title]="title === 'undefined' ? null : title"
     [attr.aria-current]="isActive"><ng-content></ng-content></a>
  `
})

    export class ONavLink implements DoCheck {
      @HostBinding('class.nav-item')

      @Input()
      public route: string;

      @Input()
      public title: string;

      @ViewChild('link')
      public link: ElementRef;

      public isActive = false;

      public ngDoCheck() {
        this.isActive = this.link.nativeElement.classList.contains('active');
      }
    }

Here's how I am using the component:

<li o-nav-link route="test">Getting tested</li>

If you have any insights on what might be causing this issue, your help would be greatly appreciated. I've been trying to troubleshoot this tirelessly!

Also, here is my module setup:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import { NgBoostedModule } from 'ng-boosted';

const approutes: Routes = [
  { path: 'test', component: AppComponent},
  { path: 'start', component: AppComponent}
  ];

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgbModule.forRoot(),
    NgBoostedModule,
    FormsModule,
    RouterModule.forRoot(approutes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

PS: The 'test' route is defined in the route array :)

Answer №1

Be sure to include RouterModule in your AppModule, and remember that [routerLink] should be an array of strings, not just a single string value.

Try binding the route property as an array of strings.

<li o-nav-link [route]="['test']">Getting tested</li>

I believe the above code will work - please verify - happy coding!!

Update:

After some investigation, I have modified the selector in the ONavLink component, which was the main cause of the issue. In your query, you are binding [route], which is not a recognized property of <li>, and that's where the problem lies.

So here is the updated version -

ONavLink.component.ts

@Component({
  selector: 'li-link',
  template: `
    <a #link [routerLink]="route" class="nav-link" routerLinkActive='active'
     [attr.title]="title === 'undefined' ? null : title"
     [attr.aria-current]="isActive"><ng-content></ng-content></a>
  `
})
export class ONavLink implements DoCheck {
  @HostBinding('class.nav-item')

  @Input()
  public route: string[];

  @Input()
  public title: string;

  @ViewChild('link')
  public link: ElementRef;

  public isActive = false;

  public ngDoCheck() {
    this.isActive = this.link.nativeElement.classList.contains('active');
  }
}

I have changed the selector to li-link and the type of the route property to string[]. You can now use the component like this

<li-link [route]="['test']">Getting Tested</li-link>

Ensure that you have the route test set up in your routes and that you are importing the necessary modules.

Hopefully, this resolves the issue for you.

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

Tips on creating a unit test for validating errors with checkboxes in your code base

In a certain scenario, I need to display an error message when a user clicks on the Next button without agreeing to the terms. To achieve this, I am looking to write a unit test case using Jest and React Testing Library. How can I go about doing this? im ...

Error in TypeScript React component due to prop-types ESLint in React

I'm in the process of setting up a typescript-react-eslint project and I've encountered an eslint error with this boilerplate component: import * as React from "react"; interface ButtonProps { children?: React.ReactNode, onClick?: (e: any) ...

Error message: "The use of Vue 3 refs in the render function is

I am facing an issue with my Vue component wherein the root element is set as ref="divRef". Strangely, when I try to access divRef.value inside the onMounted function, it returns undefined. Any assistance on this matter would be greatly appreci ...

Ensure that parameters are validated correctly in the Next.JS application router using the searchParams method

When building the page, I need to properly validate params in the Next.JS app router using searchParams. My goal is to show a main image (coverImage) for each photo on the /gallery page. When a photo is clicked, I want to display more photos of the same k ...

Is it possible to combine two separate host listeners into a single function in Angular 2?

One solution is to combine 2 different host listeners into a single function so that it can be called whenever needed. @HostListener('window:unload', ['$event']) unloadHandler() { this.eventService.send({ name: 'onUnload' }) ...

Struggling to navigate through rows in a Material UI Table

After performing a search in my TextField, the rows appear correctly in the console. However, the table itself does not update at all. I attempted to set the result of the search to a new array, but this made my TextField read-only. Any assistance with fur ...

Tips for integrating external libraries (npm packages) in Ionic 4 applications

With the changes in Ionic 4, I am seeking a definitive guide on implementing third party libraries, such as "rss-parser". I have reviewed this article which seems to be the latest resource on the topic: https://ionicframework.com/docs/v3/developer-resour ...

"Regardless of the circumstances, the ionic/angular service.subscribe event

Currently, while developing the login section of my Ionic app, I am encountering an issue with the getTokenAsObservable.subscribe() function. The main problem is that the function checks the token status when it is saved (by clicking the Login button) or ...

Tips for incorporating a mail button to share html content within an Angular framework

We are in the process of developing a unique Angular application and have integrated the share-buttons component for users to easily share their referral codes. However, we have encountered an issue with the email button not being able to send HTML content ...

Whenever I execute the 'ng serve' command, I encounter an issue with ineffective mark-compacts close to the heap limit, resulting in an allocation failure and a JavaScript

I'm currently using Angular 9 and Node.js 12. When I input ng serve, I encounter the following problem: C:\Users\homz\my-app>ng serve 93% after chunk asset optimization SourceMapDevToolPlugin vendor.js generate SourceMap <--- ...

Is there a way to go back to the previous URL in Angular 14?

For instance, suppose I have a URL www.mywebsite.com/a/b/c and I wish to redirect it to www.mywebsite.com/a/b I attempted using route.navigate(['..']) but it seems to be outdated and does not result in any action. ...

Enable the Angular button only when the radio button has been selected

Just starting out with Angular and I have a query. This is a scenario for my project at work. https://i.stack.imgur.com/R3SxA.png In this screenshot, I want to enable the "ajouter" button when at least one radio button is selected in the secure chest (s ...

Ways to retrieve an image uploaded on a nestjs server

I am facing an issue with my NestJS server where I have uploaded images but cannot access them as they appear to be some unreadable data. I have tried converting them to a blob and then setting it as an object URL for the image tag, but that also did not w ...

Encountering an error while receiving a response for the Update API request

Recently, I ventured into the world of swagger and decided to test it out with a small demo project in node-js. I successfully created 5 APIs, but encountered an issue specifically with the PUT API. Surprisingly, when testing it on Postman, everything work ...

I'm encountering an issue where the Angular application won't start on the DigitalOcean server running Ubuntu. Any

I have uploaded the distributed file of my Angular app to a server, but I am having trouble running the app on the server. Whenever I try to use ng-serve in Putty on my dist folder, I just get a blank output and nothing happens (refer to the image linked ...

Displaying data from a JSON object to a DOM table can be achieved by dynamically generating table columns based on the keys within

There is a JSON object that I'm working with: [ { "SysID": "4", "Defect Classification": "Wrong Image Color", "1": "3.0", "2": "", "3": " ...

Attempting to integrate a new feature into the smart admin platform

I've been tasked with enhancing an existing website that was originally created using the Smart Admin template. My first step is to add a new component to the dashboard. Here are the specific commands and steps I followed: -Using the command line: ...

What steps should be taken to trigger an API call once 3 characters have been entered into a field

In my current project, I am dealing with a parent and child component setup. The child component includes an input field that will emit the user-entered value to the parent component using the following syntax: <parent-component (sendInputValue)="g ...

What is the best way to find out if multiples of a specific time interval can evenly divide the time between two

I'm currently utilizing Luxon for handling dates and durations. I have two specific dates and an ISO duration, and I am looking to figure out how to determine if the interval between the dates is a multiple of the specified duration without any remain ...

The term "Movie" is not compatible as a JSX component

Currently working on a movie app project but encountering issues with handling arguments and displaying them properly using TypeScript. The challenge lies in trying to map the movie object, display them individually on the homepage, and showcase all the re ...