Angular relative routes are failing to function

I am currently working on implementing a feature module in my project and following the documentation provided.

My crisis-routing.module file looks like this:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CrisisCenterComponent } from './crisis-center.component';
import { CrisisListComponent } from './crisis-list/crisis-list.component';
import { CrisisDetailComponent } from './crisis-detail/crisis-detail.component';
import { CrisisCenterHomeComponent } from './crisis-center-home/crisis-center-home.component';

const routes: Routes = [
  {
    path: 'crisis-center',
    component: CrisisCenterComponent,
    children: [
      {
        path: '',
        component: CrisisListComponent,
        children: [
          {
            path: ':id',
            component: CrisisDetailComponent
          },
          {
            path: '',
            component: CrisisCenterHomeComponent
          }
        ]
      }
    ]
  }
];

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

While I thought I would be able to access the id with this code snippet:

 [routerLink]="['./crisis-center/..', crisis.id]"

I could use some assistance, can anyone help me?

Answer №1

In my experience, I have discovered that Angular has a recommended method for organizing parameters with child pages. The route declarations would look something like this:

children: [
      {
        path: ':id',
        component: CrisisListComponent,
        children: [
          {
            path: 'crisis-home',
            component: CrisisCenterHomeComponent
          }
        ]
      }
    ]

To access the routes, you can use the following syntax:

[routerLink]="['./crisis-center/..', crisis.id, 'crisis-home']"

This will generate the URL:

localhost/crisis-center/1/crisis-home

Answer №2

While I have successfully implemented some functionality, I am facing challenges when it comes to working with nested children.

My updated routes are as follows:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CrisisCenterComponent } from './crisis-center.component';
import { CrisisListComponent } from './crisis-list/crisis-list.component';
import { CrisisDetailComponent } from './crisis-detail/crisis-detail.component';
import { CrisisCenterHomeComponent } from './crisis-center-home/crisis-center-home.component';
import { CrisisDetailedComponent } from './crisis-detailed/crisis-detailed.component';

const crisisRoutes: Routes = [
  {
    path: 'crisis-center',
    component: CrisisCenterComponent,
    children: [
      {
        path: '',
        component: CrisisListComponent,
        // children: [
        //   { path: '', component: CrisisCenterHomeComponent },
        //   { path: 'crisis/:id', component: CrisisDetailedComponent },
        // ]
      },
      { path: ':id', component: CrisisDetailedComponent },
      { path: 'home', component: CrisisCenterHomeComponent },
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(crisisRoutes)],
  exports: [RouterModule]
})
export class CrisisCenterRoutingModule { }

I'm puzzled as to why only one nested route is being accepted; it's possible that I am not accessing the routes correctly.

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

Angular - Ensure completion of a function call before continuing with the code execution

I'm currently working on developing a code snippet that checks for potential adverse drug reactions between two medications. Within my checkForClash() function, there is a call to getCollisionsList(), which is responsible for populating the interacti ...

Enhance your images with the Tiptap extension for customizable captions

click here for image description I am looking to include an image along with an editable caption using the tiptap extension Check out this link for more information I found a great example with ProseMirror, but I'm wondering if it's possible ...

Issue: When a function within a subscribe method does not return a value and its declared type is not 'void' or 'any', a TypeScript error occurs

In my Angular 2 project, I've created a basic service to check if the user is logged in. This service verifies the existence of the user object within the FirebaseAuth object. However, I encountered an error stating "lack of return statement" even tho ...

Every time Chrome on Android returns a keyCode of 229

Here is a snippet of code that I am having trouble with: ... @HostListener('keydown', ['$event']) onKeyDown(evt: KeyboardEvent) { console.log('KeyCode : ' + evt.keyCode); console.log('Which : ' + evt.which); ...

Ensure that compiler errors are eliminated for object properties that do not exist

Coming from a JavaScript background, I recently began working with Angular 2 and TypeScript. Below is a snippet of my code: export class AddunitsComponent implements OnInit { public centers:any; constructor(){ this.centers = {}; }} In my view, I h ...

The modal feature on ng-bootstrap.github.io is failing to function properly when used with the Bootstrap3 CSS

Struggling to understand why the modal displays when using Bootstrap 4 with ng-bootstrap, but not displaying with Bootstrap 3. ...

I'm attempting to integrate Angular Material into my project but I'm struggling to figure out how to resolve the issue

npm ERR! code ERESOLVE npm ERR! ERESOLVE was unable to find a resolution npm ERR! While resolving: [email protected] npm ERR! Found: [email protected] npm ERR! node_modules/tslint npm ERR! dev tslint@"~6.1.0" from the root projec ...

Angular interceptor allows the execution of code after the outgoing request has completed its process

In the process of creating a simple interceptor, I have encountered an issue. The interceptor is designed to check if an outgoing request is targeting a specific endpoint type, namely events and favoriteevents. While the interceptor works almost as intend ...

Before fetching the data from firebase in Angular 2, it is crucial to ensure that the code is properly

I'm facing an issue when trying to retrieve data from Firebase. It successfully retrieves the data, but it takes a few seconds to do so. In the meantime, the code continues running and the variable's value becomes null. Why is this happening? Is ...

Strategies for Dealing with 'No Search Results' in Your Search Functionality

I am currently facing an issue with displaying "No Results Found" when a user utilizes my search feature. The current problem is that "No Results Found" appears immediately on the screen and then disappears while a search query is being processed, only to ...

What is the best way to retrieve the overall count of a field within a reactive form, while also identifying both the valid

In the form I am working on, some fields are required while others are not. I am trying to figure out how many total fields there are and how many have been filled correctly without breaking any validation rules, even if they are not marked as required. I ...

Typescript declaration for a .js file in a diverse project

Hey there! I'm currently in the process of converting my JavaScript React Redux project to TypeScript, and I've decided to kick things off by tackling my redux reducers file. Here's a snapshot of how my project is structured: Project/ .. ...

Insert an HTML element or Angular component dynamically when a specific function is called in an Angular application

Currently, I am working on a component that contains a button connected to a function in the .ts file. My goal is to have this function add an HTML element or make it visible when the button is clicked. Specifically, I would like a dynamic <div> elem ...

What is the process of expanding types definitions by incorporating custom types?

I added these custom types to my project. The file structure can be found here. However, these types do not contain certain useful types such as ClientState. I want to include the following enum in those types: enum ClientState { DISCONNECTE ...

Defining the type of the createAction() function in TypeScript within the context of Redux Toolkit

Lately, I have been delving into the redux-toolkit library but I am struggling with understanding the type declaration of the createAction function as demonstrated below. The createAction function returns a PayloadActionCreator which includes a generic of ...

Console not logging route changes in NextJS with TypeScript

My attempt to incorporate a Loading bar into my NextJs project is encountering two issues. When I attempt to record a router event upon navigating to a new route, no logs appear. Despite my efforts to include a loading bar when transitioning to a new rout ...

What is the best way to retrieve a property from a conditional type using generics?

The code snippet above presents an issue in TypeScript: const exampleFn = function<AttributeName extends 'attributeA' | 'attributeB'>( whatToProcess: AttributeName extends 'attributeA' ? {attributeA: string} : {attri ...

The code below is not working as it should be to redirect to the home page after logging in using Angular. Follow these steps to troubleshoot and properly

When looking at this snippet of code: this.router.navigate(['/login'],{queryParams:{returnUrl:state.url}}); An error is displayed stating that "Property 'url' does not exist on type '(name: string, styles: AnimationStyleMetadata". ...

Alert for timeout triggered without any error logs recorded

While working on a login & register page, I encountered an issue. After clicking the register button, a timeout alert error appeared despite no log errors being present. However, the data used to register was successfully saved in the MYSQL database. ...

Inheritance-based generic type inference in Typescript

Take a look at this piece of code: class A<T> { t?: T; } interface B {} class C implements A<B> {} function f<T1 extends A<T2>, T2>(a: T1): T2 | undefined { return a.t; } const result = f(new C()); const result2 = f(new A<B> ...