Navigating through various product categories in Angular's routing system

Greetings! I am currently building a Shop Page in Angular 4 and encountering an obstacle with Angular routing. The issue arises when a user clicks on a product category, the intention is for the website to direct them to the shop page.

On the homepage, there are two links provided under product categories -

<h2>Product Categories</h2>
<a [routerLink]="['/shop', id]>Jeans</a>
<a [routerLink]="['/shop', id]>Shirts</a>

For the shop page component, I've created a service to retrieve data from a JSON file

export const PRODUCTS: Products[] = [
{
    id: 1,
    productCat:'Jeans',
    product: [
        {
            prodId: 1a,
            productName: 'Trendy Jeans',
        },
        {
            prodId: 2a,
            productName: 'Trendy Jeans second product',
        },
    ],
},
{
    id: 2,
    productCat:'Shirts',
    product: [
        {
            prodId: 1b,
            productName: 'Trendy Shirts',
        },
    ],
},
]

When a user selects jeans, only jean products should be displayed, and clicking on shirts should reveal shirt products exclusively.

Below is my app routing module -

app-routing.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { routes } from './routes';

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

routes.ts file -

export const routes:Routes = [
    {path: 'home', component: HomeComponent},
    {path: 'shop/:id', component: ShopComponent},
    {path: '', redirectTo: '/home', pathMatch: 'full'}
];

Therefore, when selecting jeans or shirts, the component should filter and display the respective products accordingly. Is it possible to achieve this within the same component?

Answer №1

In Angular, it is recommended to utilize the Angular routerLink attribute instead of using href for navigation purposes.

<a [routerLink]="['/shop', id]"> Shop Now</a>

Answer №2

If you want to set up routing in angularjs, make sure to include the routerLink attribute in your anchor tags and use the router-outlet tag on your home page to show the response of the router Link.

<h2>Product Categories</h2>
<a routerLink="shop/:id">Jeans</a>
<a routerLink="shop/:id">Shirts</a>

To display the contents of the Shop component.html in appcomponent.html, insert the following tag:

<router-outlet>

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

Issue: The component factory for GoogleCardLayout2 cannot be located

Recently I've been working on an Ionic 3 with Angular 6 template app where I encountered an issue while trying to redirect the user to another page upon click. The error message that keeps popping up is: Uncaught (in promise): Error: No component fac ...

Angular overlooks file-loader during AOT compilation

I am working on creating a documentation website using Angular. The docs will be written in markdown and displayed through the ngx-markdown plugin. While everything works perfectly fine on a JIT build, I am facing an issue where AOT build always removes th ...

Having trouble getting my specialized pipe (filter) to function properly in Angular 2

I have implemented a custom pipe for filtering data in my table. Oddly, when I enter a search string into the input box, it correctly prints 'found' in the console but no rows are displayed in the table. However, if I remove the pipe altogether, ...

Transform a typical EF list into a structured JSON format

On my ASPX page, I have a WEB Method that uses Entity Framework to retrieve a List from the SQL DB. Using rep As New RBZPOSEntities q = rep.getSalesByLocation(fDate, tDate).ToList End Using Afterwards, I utilize javascriptserializer to co ...

The unsightly square surrounding my sprite in Three.js

I am attempting to create a beautiful "starry sky" effect using Three.js. However, I am encountering an issue where my transparent .png star sprites have a colored outline around them. Here is the sprite I am using: https://i.sstatic.net/2uylp.png This ...

Creating a JSON formatting structure with three layers of nesting

My goal is to create a jQuery script that will automatically populate a select box with a name and an ID based on the user's selection from another select box. However, I'm encountering difficulties in structuring my JSON file. Here are the attr ...

How to generate a custom JSON key name in PHP using Laravel

Currently, I am utilizing imagick to extract a number of pages and then store it in JSON format. However, the number is stored as is without any key, for instance - 20. I am seeking a way to store the number with a specific key like below: { "pages": " ...

How can you define types for abstract React components in Typescript?

Currently facing a challenge when it comes to typing an abstract component in Typescript, especially after having extensive experience with Flow. The code snippets below are based on Typescript 3.8.3. Here is the relevant code: const useSlot = (): [React ...

Custom attributes given to Stencil web components in Vite/Vue3 will not trigger any reactions

Short backstory I initially set up my project with a vue-cli environment using Vue 2 and options-api. Recently, I decided to transition to create-vue, which is based on Vite with Vue 3 and Typescript. To incorporate web components from Stencil into my pro ...

Utilizing lodash and Angular 8: Identifying an valid array index then verifying with an if statement

In my current project, I am developing an e-commerce angular application that includes a basket with two types of products: restaurant + show combos and gift cards. When a client reserves a restaurant, they must also reserve a show; conversely, the client ...

Is the combination of react-router and express causing issues with logging out?

My Configuration: I am using react router to manage component changes and express for handling get requests from my database. The React server is running on port 3000 The Express server is running on port 5000. In React, there is a setupProxy.js file i ...

What is the best way to bring attention to a field that is outside the current viewport?

Is there a way to automatically scroll to the specific invalid field after clicking on submit in a large form, without having to manually search for it by scrolling through the page? ...

Is it possible to merge these two scripts into a single one within Vue?

As a newcomer to VUE, I am faced with the task of modifying some existing code. Here is my dilemma: Within a single component, there are two script tags present. One of them contains an import for useStore from the vuex library. The other script tag incl ...

The attribute 'name' cannot be found within the class 'MyComponent'

I'm a beginner in Angular2 and I have no previous knowledge of version 1. Can you help me understand why this error is occurring and guide me on how to fix it? import { Component } from 'angular2/core'; @Component ({ selector: 'my- ...

Zend Framework causing issues with Jquery Ajax - encountering parsererror with Json output

I'm new to using the zend framework and am struggling to pass an array from a controller to a jQuery AJAX function in the view. I keep receiving errors when I change the 'dataType' to 'json'. Can someone please help me understand ...

Retrieve information using an asynchronous pipeline once the screen is fully loaded

In my table component, I have integrated functionality for data reloading and filtering. These actions are powered by Subjects: private fetchFromServer$ = new Subject< void >(); private filter$ = new Subject< void >(); The data fetching proces ...

Troubleshooting: Issue with reloading in MERN setup on Heroku

I successfully deployed my MERN stack application on Heroku using the following code: import express from "express"; import path from "path"; const app = express(); const port = process.env.PORT || 5000; app.get("/health-check&qu ...

Typescript's Nested Type Assignments

Simply put, I'm making an API call and receiving the following data: { getUserInfo: { country: 'DE', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c48594f487c59445d514c5059125f5351">[e ...

Load a React component in the same spot when clicked

Is there a way to implement a functionality where clicking on different buttons in a panel will display different components in the same location? <AddNotification /> <EditNotification /> <DeleteNotification /> const AdminPanel = () =& ...

How do I correctly specify the parameter type of a function when passing a React functional component as an argument in TypeScript?

I am facing an issue with type declaration for function parameters. See the code snippet below, const FunctionalComponent = ({propA,propB}: FunctionalComponentProps): JSX.Element => { return } Now, I need to pass the FunctionalComponent as a parame ...