The router is unable to direct when an item is clicked

I am encountering an issue with my routing setup - when I click on an item in the list-item component, it does not successfully route to the detail-component. Here is a glimpse of my source code:

product-list.component.html:

<h1>Product List Component</h1>
<ul class="products">
   <li *ngFor="let product of products">
      <a routerLink="/detail/{{product.id}}">
         <span class="badge">{{product.id}}</span> {{product.name}}
      </a>
   </li>
</ul>

product-detail.component.ts

export class ProductDetailComponent implements OnInit {

constructor(
  private route: ActivatedRoute,
  private productService: ProductService
) { }

ngOnInit() {
  this.getProduct();
}

private getProduct(): void {
  const id = +this.route.snapshot.paramMap.get('id');
  this.productService.getProductById(id);
}

}

product-detail.component.html:

<p>Just one line to test routing to this component</p> 

ProductService.ts

@Injectable({
 providedIn: 'root'
})
export class ProductService {

constructor() { }

getAllProduct(): Product[] {
  return arrayProduct;
}

getProductById(id: number): Product {
  const product = arrayProduct.find(product => product.id === id);
  return product;
}

}

Router

const routes: Routes = [
{ path: 'detail/:id', component: ProductDetailComponent }
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

Here is an image view of the list-item component https://i.sstatic.net/f3xAj.png

If anyone can provide assistance, I would greatly appreciate it. Thank you!

Answer №1

It seems like you may not be utilizing the router link correctly.

Consider using a structure similar to this:

<h1>Product List Component</h1>
<ul class="products">
   <li *ngFor="let product of products">
      <a [routerLink]="['/detail/',product.id]">
         <span class="badge">{{product.id}}</span> {{product.name}}
      </a>
   </li>
</ul>

Make sure to follow the correct syntax for the routerLink directive to avoid issues.

Answer №2

It is important to make the correct adjustments in your code

<h1>Product List Component</h1>
<ul class="products">
   <li *ngFor="let product of products">
      <a routerLink="/detail/{{product.id}}">
         <span class="badge">{{product.id}}</span> {{product.name}}
      </a>
   </li>
</ul>

Revise

<a routerLink="/detail/{{product.id}}">
to

<a [routerLink]="['/detail/',product.id]">

This adjustment ensures that the route is invoked correctly. The routerlink needs to be enclosed in square brackets, like so :-

[routerLink]="['YOUR ROUTE HERE']"
. Also, it is assumed that you have properly configured the routing module in the relevant app.module.ts file.

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

Can someone guide me on the proper implementation of the 'useEffect' hook in React version 18?

I'm currently working on a project following a YouTube tutorial that uses React 17, while I'm using React 18. Everything has been going smoothly so far, but I've hit a roadblock with formatting animated text. The specific task I'm stuck ...

Ways to identify the specific occurrence when the nth image is displayed within a div containing an image slider

I am working on an image carousel with unique elements for each slide: <div class="outer_wrapper_hide" id="outer_wrapperID"> <div class="inner_wrapper" id="inner_wrapperID"> <img id="slideimage1" class="slideimage" height="500" ...

Utilizing Typescript to Inject Generics and Retrieve the Name of an ES6 Module

I am currently working on developing a versatile repository using: Typescript ES6 Angular 1.x However, I am facing challenges in determining the correct way to inject the Entity and retrieve its module name. The main reason for needing the name: I adh ...

What's causing ng-show to malfunction in IE11 on AngularJS?

I am experiencing a strange issue with my code - ng-show works perfectly fine on Firefox, but not on IE 11. <div ng-show="isExist" class="panel panel-default"> Here is the relevant code snippet from the controller: $scope.isExist = false; if(user ...

Stop a loop that includes an asynchronous AJAX function

Embarking on my Javascript journey as a beginner, I find myself facing the first of many questions ahead! Here is the task at hand: I have a directory filled with several .txt files named art1.txt, art2.txt, and so on (the total count may vary, which is ...

What is the purpose of using CORS with Express?

Here is how my express server setup looks: const cors = require('cors'); const express = require('express'); const app = express(); const port = 8000; app.use(cors({origin: 'http://localhost:8000'})); // Handle requests of c ...

Experiencing difficulty in connecting with the service providers

What's the process for obtaining these providers? I recently followed the JavaScript Mastery tutorial step by step, however, I encountered an issue with the useEffect hook to fetch the providers (I even tried using alert to check, but it keeps showin ...

Is it possible to execute "green arrow" unit tests directly with Mocha in IntelliJ IDEA, even when Karma and Mocha are both installed?

My unit tests are set up using Karma and Mocha. The reason I use Karma is because some of the functionality being tested requires a web browser, even if it's just a fake headless one. However, most of my code can be run in either a browser or Node.js. ...

Trouble getting CSS and Javascript to bind when dynamically appending HTML elements

Attempting to dynamically bind HTML from an Angular controller SkillsApp.controller('homeController', function ($scope, $http, $q, $timeout) { $scope.getAllCategories = function () { $http({ url: "/Categories/GetAllCategories", ...

Navigating React: Learn the ins and outs of accessing and modifying state/attributes from a different component

Looking to update the attribute values of ComponentB from ComponentA (currently using an index). I attempted to call lower component functions to modify their state/values. import React from 'react' class TaskComp extends React.Component{ ...

Ways to access a JavaScript object beyond the function scope

Using the code below, I am able to retrieve JSON data when an element is clicked. This data is then used to create a table, fill the cells with images, and append the table to a specific div. function LoadImagesByCategory() { $.getJSON("/Service/GetJs ...

What is causing the error "Next is not a function" to occur when exporting a Middleware function to the module.exports object?

In my logger.js module, I have a middleware function that I import into app.js and utilize. // ------ File : logger.js ------ // function log(req, res, next) { console.log('Logging details ... '); next(); } module.exports = log; // ---- ...

Determining the Area of a Polygon Based on its Slope or Angle

Is it possible to calculate the area of a polygon when it has an inclination or slope? I have both the angle/slope and the points of the polygon, and I need to determine the area. How can this be achieved? ...

nodemon keeps attempting to restart the server after making changes to files, but the updates are not being reflected

I've been using the nodemon package, but I'm experiencing issues with it not restarting the server properly. Instead of showing "server running" after making changes like in tutorials, all it displays is "restarting due to changes". This also res ...

How to retrieve JSON data in Angular.js

I'm having trouble accessing a json file in angular.js with the code below. I keep getting an error message and could really use some help! Here is my module : angular.module("demoApp", ['demoApp.factory','demoApp.controllers']); ...

The useEffect hook is failing to resolve a promise

I have received a response from an API that I need to display. Here is a snippet of the sample response (relevant fields only): [ { ...other fields, "latitude": "33.5682166", "longitude": "73 ...

Ways to resolve Cross-Origin Resource Sharing (CORS) issue encountered in Report

I am currently working on an Angular project and trying to render SSRS reports within the app by utilizing a specific package. The application is hosted at http://localhost:52698/ while the SSRS server resides on a different domain http:\ssrsserv ...

An issue has occurred while utilizing Angular

I'm diving into the world of Angular and encountering some errors as I try to execute this code. An unexpected token is causing trouble. A constructor, method, accessor, or property was expected. The left side of a comma operator seems to be unused ...

Unable to modify the value of data using the data() method

Just a basic HTML code snippet <div class="this" data-info="false"></div> $('.this').data('info'); This will correctly output: false $('.this').data('info', 'true'); data-info remains u ...