Can someone show me how to properly set up nested child routes in Angular 2?

My application structure is organized as shown below

.
├── photos
├── posts
├── users
│   ├── detail
│   │   ├── address
│   │   ├── family
│   │   ├── information
│   │   └── phones
│   ├── friends
│   └── profile
└── videos

When creating nested routes, I prefer to keep routes at the same level within their own level.

For example:

First-level routes are placed in the root routes. Second-level routes go to the users routes and third-level routes go to the detail route.

Therefore, the root routes look like this,

const appRoutes: Routes = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'photos',
    component: PhotosComponent
  },
  {
    path: 'posts',
    component: PostsComponent
  },
  {
    path: 'users',
    component: UserListComponent
  },
  {
    path: 'user/:username',
    component: UserComponent
  },
  {
    path: 'videos',
    component: VideosComponent
  }
]
export const AppRoutes = RouterModule.forRoot(appRoutes);


// for the user routes,


const userRoutes: Routes = [
  {
    path: 'detail',
    component: DetailComponent
  },
  {
    path: 'friends',
    component: FriendsComponent
  },
  {
    path: 'profile',
    component: ProfileComponent
  }
]
export const UserRoutes = RouterModule.forChild(userRoutes);

// for the detail routes,


const detailRoutes: Routes = [
  {
    path: 'address',
    component: AddressComponent
  },
  {
    path: 'family',
    component: FamilyComponent
  },
  {
    path: 'info',
    component: InformationComponent
  },
  {
    path: 'phones',
    component: PhonesComponent
  }
]
export const DetailRoutes = RouterModule.forChild(detailRoutes);

I am struggling with mixing the given routes together. I want the route to be /users/:username/detail/info but I can't seem to figure out how to link them.

Answer №1

To assign routes to children, you can utilize the children attribute. If you prefer keeping them in separate files, consider exporting an array of Routes (not the RouterModule) and importing them as needed. For example:

User Routes:

export const userRoutes: Routes = [
  {
    path: 'profile',
    component: ProfileComponent
  },
  {
    path: 'settings',
    component: SettingsComponent
  }
]

App Routes:

import {userRoutes} from './user/user.routes'

const appRoutes: Routes = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'articles',
    component: ArticlesComponent
  },
  {
    path: 'contact',
    component: ContactComponent
  },
  {
    path: 'dashboard',
    component: DashboardComponent
  },
  {
    path: 'user/:id',
    component: UserComponent,
    children: [userRoutes[1]]
  },
  {
    path: 'videos',
    component: VideosComponent
  }
]
export const AppRoutes = RouterModule.forRoot(appRoutes);

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

A guide to incorporating border radius to images within a composite image with sharp.js in Node.js

In my Node.js project, I am using the sharp library to combine a collection of images into a single image. Although I have successfully created the composite image, I now need to add a border radius to each of the images in the grid. Here is the code snip ...

Add one string to an existing array

I have a component named ContactUpdater that appears in a dialog window. This component is responsible for displaying the injected object and executing a PUT operation on that injected object. The code for the component is shown below: HTML <form [for ...

Transferring information from a chosen <mat-option> to a different component in Angular Material

I am currently facing an issue with two components in my Angular application. The first component includes an Angular Material mat-option to select an option from a dropdown menu, while the second component is supposed to display the selected data. I attem ...

Unable to retrieve device UUID using capacitor/device on Android

I'm currently attempting to obtain the UUID of my devices so that I can send targeted notifications via Firebase. My front end and back end are connected, enabling the back end to send notifications to the front end using Firebase. However, all I am a ...

Angular 5 update causing 'NgModule not found' error

After attempting to upgrade my app to Angular 5, I encountered a series of bugs. Among them, there is one persistent issue that has me stumped. An uncaught error has surfaced: 'Unexpected value HttpClient imported by the module AppModuleShared. Ple ...

Is it possible to set up a universal type definition in TypeScript version 2 and above?

I have a collection of straightforward .ts files, not part of any projects but standalone .ts scripts. They implement certain node.js features. Both TypeScript and node type definitions are set up through the following commands: npm install -g typescript ...

Assign the onClick function to the decoration of a Vscode extension

When I click on a vscode decoration, I want to trigger a function. Here's the code I created for this: const decoration = { range, hoverMessage: `${command} ${input}`, command: { title: 'Run Function', command: ' ...

Having trouble extracting a list of matches using a Regular Expression?

const stringWithDate: string = "4/7/20 This is a date!"; const reg: RegExp = new RegExp("^(\d{1,2}\/\d{1,2}\/\d{1,2})").compile(); const exist: boolean = reg.test(stringWithDate) const matches: RegExpExecArray | null = reg.exec(str ...

Is it possible to change the value of a react-final-form Field component using the onSelect function?

I am currently working on a React application using TypeScript and incorporating the Google Places and Geocoder APIs through various React libraries such as "react-places-autocomplete": "^7.2.1" and "react-final-form": "^6.3.0". The issue I'm facing ...

I am currently working on establishing a connection between Angular and MongoDB

I built a basic Angular application currently running on Local Host 4200. What is the process for saving form values and storing them in a MongoDB database? ...

Efficient method for iterating through three arrays that have matching values and satisfy specified conditions in TypeScript

Struggling to speed up my Excel sheet creation time, currently taking over 20 seconds. I'm using the code below to compare three arrays and get the desired output: for (let i = 0; i < this.arrayNumberOne[0].length; i++) { let orangeOne = this.a ...

.Net Core receives the method name instead of the parameter value passed by TypeScript

Can someone explain why the code is passing "getFullReport" as the eventId instead of the actual value while making its way to the .Net Core 3.1 side? Prior to the call, I double-checked with a console.log to ensure that eventId holds the correct ID I am ...

Avoid using unnecessary generic types while updating a TypeScript interface on DefinitelyTyped, especially when using DTSLint

After attempting to utilize a specific library (query-string), I realized that the 'parse' function was returning an any type. To address this, I decided to update the type definitions to include a generic. As a result, I forked the DefinitelyTy ...

Tips for testing an Angular service method that returns a JSON object

I have a service in Angular that processes JSON input and returns JSON output after some operations. My positive test case for this service is failing consistently. I suspect the reason for this failure might be: Expected Result : [ Object({ key: &apos ...

Working with Typescript to map and sort the key values of a new datasource object

Managing a large datasource filled with objects can be challenging. My goal is to rearrange the order of objects in the array based on new values for each key. Whenever a new value for a key is found, I want the corresponding object to move to the top of t ...

OpenTok Angular 6 encountered an error with code TS2314 stating that the generic type 'Promise<T>' needs to have 1 type argument specified

Issue in opentok.d.ts File: Error TS2314 npm version: 6.2.0 node: v8.10.0 Angular CLI: 6.2.3 Operating System: Linux x64 Angular Version: 7.0.0-beta.5 @opentok/client": "^2.14.8 ...

Discovering the position of an element within an array and leveraging that position to retrieve a corresponding value from a separate array

const STATE = ["TEXAS","CALIFORNIA","FLORIDA","NEW YORK"] const STATE_CODE = ["TX","CA","FL","NY"] With two arrays provided, the first array is displayed in a dropdown menu. The challenge is to retrieve the corresponding state code from the second array ...

Understanding the appropriate roles and attributes in HTML for a modal backdrop element in a TypeScript React project

Trying to create a Modal component using React and TypeScript with a feature that allows closing by clicking outside. This is being achieved by adding a backdrop element, a greyed out HTML div with an onClick event calling the onClose method. Encountering ...

Steps to resolve the 'form' variable being assigned a value but never used in axios:

I am encountering an issue with a contact form that utilizes React with axios on the frontend and Express with nodemailer on the backend while running locally. The expected outcome is for me to receive an email when I click the "Submit" button. However, up ...

How can I automatically select the first radio button using Angular?

I am facing an issue with displaying a dynamic list of radio buttons, where the first one always needs to be pre-selected. Initially, I used: [checked]="i === 0" Then, when I added: [(ngModel)]="item.modifType" The first radio button was no longer sele ...