The routerlink feature consistently directs back to the default page

I am facing an issue where my routerlink does not redirect me to the correct path in app.routes.ts when clicked. Even though the routerlinks are set as 'user/teams' and 'user/dashboard' respectively.

I can access the pages by directly going to "/user/dashboard" or "/user/teams", but when using routerlink, it navigates me to the wrong component.

This is how I have configured my router:

Here is my app.routes.ts:

import { Routes } from '@angular/router';
import { HomeComponent } from './view/home/home.component';
import { UserComponent } from './shared/layouts/user/user.component';

export const routes: Routes = [
{
    path: '', 
    pathMatch: 'full', 
    component: HomeComponent
},
{
    path:'user',
    loadComponent: () => UserComponent,
    children: [
       {
            path:'',
            loadChildren: () => import('./view/user/user.routes').then((m) => m.routes)
       }
    ]
}
];

I also have a separate routes file named user.routes.ts:

import { Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { TeamsComponent } from './teams/teams.component';

export const routes: Routes = [
    {
      path: 'dashboard',
      loadComponent: () => DashboardComponent,
    },
    {
      path:'teams',
      loadComponent: () => TeamsComponent
    }
    ,
    {
        path: '',
        pathMatch: 'full',
        redirectTo: 'dashbaord',
    } 
];

Here is my user.component.html which includes the <router-outlet>.

<main class="d-flex flex-nowrap">
    <app-side-menu></app-side-menu>
    <div class="container-fluid p-5">
        <router-outlet></router-outlet>
    </div>
</main>

The side menu in my application contains the following routerlinks. The side-menu.component.html:

<li>
  <a href="#" routerlink="/user/dashboard" class="nav-link link-body-emphasis">
    <svg class="bi pe-none me-2" width="16" height="16"><use xlink:href="#speedometer2"></use></svg>
    Dashboard
  </a>
</li>
<li>
  <a href="#" routerlink="/user/teams" class="nav-link link-body-emphasis">
    <svg class="bi pe-none me-2" width="16" height="16"><use xlink:href="#table"></use></svg>
    My Teams
  </a>
</li>

and this is the implementation in side-menu.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-side-menu',
  standalone: true,
  imports: [],
  templateUrl: './side-menu.component.html',
  styleUrl: './side-menu.component.scss'
})
export class SideMenuComponent {

}

I appreciate any assistance with resolving this issue!

Answer №1

@Naren's solution should help fix your routing problem. Here is an adjusted version:

  1. Instead of using children, utilize loadChildren for the routes in the app.route.ts

app.route.ts

export const routes: Routes = [
  {
    path: 'user',
    loadChildren: () => UserComponent,
    loadChildren: () => import('./view/user/user.routes').then((m) => m.routes),
  },
  {
    path: '',
    pathMatch: 'full',
    component: HomeComponent,
  },
];

user.routes.ts

export const routes: Routes = [
  {
    path: 'dashboard',
    loadComponent: () => DashboardComponent,
  },
  {
    path: 'teams',
    loadComponent: () => TeamsComponent,
  },
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'dashboard',
  },
];
  1. Add the RouterModule to the SideMenuComponent.
import { RouterModule } from '@angular/router';

@Component({
  selector: 'app-side-menu',
  templateUrl: './side-menu.component.html',
  styleUrls: ['./side-menu.component.css'],
  standalone: true,
  imports: [RouterModule]
})
export class SideMenuComponent { ... }
  1. Note that there is a typo error, it should be routerLink instead of routerlink.
<li>
  <a href="#" routerLink="/user/dashboard" class="nav-link link-body-emphasis">
    ...
  </a>
</li>
<li>
  <a href="#" routerLink="/user/teams" class="nav-link link-body-emphasis">
    ...
  </a>
</li>

Check out the demo on StackBlitz

Answer №2

Kindly update the application routing with the following changes:

import { Routes } from '@angular/router';
import { HomeComponent } from './view/home/home.component';
import { UserComponent } from './shared/layouts/user/user.component';

export const routes: Routes = [
{
    path: '', 
    pathMatch: 'full', 
    component: HomeComponent
},
{
    path:'user',
    loadChildren: () => import('./view/user/user.routes').then((m) => m.routes)
}

];

Please adjust the routing for users to be as follows:

import { Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { TeamsComponent } from './teams/teams.component';

export const routes: Routes = [
{ path: '', component: UserComponent ,children:[
    {
      path: 'dashboard',
      loadComponent: () => DashboardComponent,
    },
    {
      path:'teams',
      loadComponent: () => TeamsComponent
    }
    ,
    {
        path: '',
        pathMatch: 'full',
        redirectTo: 'dashbaord',
    }
    ]
}
];

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

typescript decorator implemented on a class that is nested within another class

Is it possible to decorate a nested property within a class? Let's explore with an example: function log(name: string = 'DecoratedProp') { return function logHandler(target: any, field: any) { // get the key ...

Displaying a component inside a different component

I'm attempting to display components inside another component, but even when I try to include div elements within the component, they don't show up. const DisplayComponent = () => { return ( <div> <DisplayContent ...

What is the best technique for verifying the existence of data in the database before making updates or additions with Angular's observables?

I am facing a straightforward issue that I need help with in terms of using observables effectively. My goal is to search my database for a specific property value, and if it exists, update it with new data. If it does not exist, then I want to add the new ...

The jsPdf library performs well on medium-sized screens like laptops, but when downloaded from larger monitor screens, the PDF files do not appear properly aligned

In the code snippet below, I am using html2canvas to convert HTML to PDF. The PDF download works fine on medium screens, but when viewed on larger screens, some pages appear blank and the content order gets shuffled. How can I resolve this issue so that th ...

Getting the route parameter in Angular 2 is easy with the stable router

Currently working with the latest stable Angular 2 RC version. Unfortunately, the documentation for the new router component has yet to be completed. Struggling to retrieve a parameter from a navigated page. Defined routes: @Routes([ {path: '/resu ...

Decide on the return type of a generic function depending on the parameters of the function

I have a series of TypeScript functions that are structured as follows: useCustomFunction = <T>(key: CustomType) : T => { // implementation details here } The parameter type is restricted to a specific set of strings: type CustomType = "apple ...

Error occurs when the directive is not being applied due to the usage of the "attr" host attribute

Referring to a post about host attributes, I have developed a Plunker for demonstration purposes. Upon reviewing the github issue, it seems that using [attr.someDirective] should allow us to selectively apply a directive attribute to an element. Although ...

Incorporating a class element within an Angular 2 directive

When working with Angular 2 directives, one way to add an element is by using the following code: this._renderer.createElement(this._el.nativeElement.parentNode, 'div'); After adding the element, how can I set its class and keep a reference to ...

What is the process for updating the background color of the header in ngx datatable?

I am looking to change the background color of the table header to blue. This is the HTML code I have: <ngx-datatable class="material" [rows]="rows" [columnMode]="'force'" [headerHeight]="50" [footerHe ...

Optimizing the utilization of multiple ngIf statements in Angular 5

I am new to Angular development and I'm currently working with *ngIf statements in my components. While researching, I came across articles advising against using complex logic in *ngIf statements. For instance: <user-component *ngIf="role= ...

`How to utilize the spread operator in Angular 4 to push an object to a specific length`

One issue I'm facing is trying to push an object onto a specific index position in an array, but it's getting pushed to the end of the array instead. this.tradingPartner = new TradingPartnerModel(); this.tradingPartners = [...this.tradingPartner ...

Angular: leveraging the power of *ngFor and *ngIf while incorporating index values in nested components

I want to display various items from an array observable within grid-card components. I also aim to restrict the number of grid cards displayed based on specific variables in my component, such as gridCols*maxRows, by utilizing a conditional check with *ng ...

Tips for creating unit tests for methods in Angular components with jasmine

As a beginner in jasmine unit testing, I am struggling to understand how to write and implement tests in jasmine. I have been encountering numerous errors along the way. Is there anyone who can assist me with writing a unit test for the code snippet below ...

Unable to locate the API compiler-cli and the VERSION function

After downloading a repository from GitHub to run an Angular project, I typically use the command npm install to add node modules to the project. However, when I then attempt to run ng serve, I encounter the following error: https://i.stack.imgur.com/xiqo ...

Build an object using a deeply nested JSON structure

I am working with a JSON object received from my server in Angular and I want to create a custom object based on this data. { "showsHall": [ { "movies": [ "5b428ceb9d5b8e4228d14225", "5b428d229d5b8e4 ...

Steps for connecting data to a react table

This is my first time working with React and I want to display the following data (id, name, status, and quantity): interface Goods { id: number; name: string; status: string; quantity?: number; } export const getGoods = (): Promise<Goods[]> ...

The CSS properties intended for ion-button elements are not taking effect

I'm attempting to set a background color when a ion-button is clicked or maintain the ion-ripple effect after it has filled the button in Ionic 4. I experimented with applying custom CSS states in global.scss, but encountered issues where the active ...

Combining Bazel, Angular, and SocketIO Led to: Unforeseen Error - XMLHttpRequest Not Recognized as Constructor

I am looking to integrate ngx-socket-io into my Angular application. I utilize Bazel for running my Angular dev-server. Unfortunately, it seems that ngx-socket-io does not function properly with the ts_devserver by default. Upon checking the browser consol ...

Exploring Angular: Unraveling the Mystery of Accessing Nested Arrays in Objects

Looking into an Angular-14 application, a JSON response is retrieved: { "data": { "pageItems": [ { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "merchantId": "3fa85f64-5717 ...

Angular 9 TestBed RouterTestingModule: Exploring the router.url Readonly Property

While transitioning from Angular 8 to Angular 10 in stages, I encountered an issue when upgrading to version 9. All of my TestBed.get(Router).url calls started throwing errors because the property had become read-only. For instance, the code TestBed.get(R ...