Navigate between Angular Child Routes without requiring the Parent Route

In my Angular 13 application, I have implemented routes that lead to various modules with their own set of child routes.

The routing configuration for each module looks like this:

@NgModule({
    declarations: [DashboardComponent],
    imports: [RouterModule.forChild(childRoutes)]})
export class ChildModule{}

export const childRoutes = [
    {path: 'dashboard', component: DashboardComponent},
    {path: 'reports', component: ReportsComponent}];

Within the parent module, the child module is lazy loaded using the following setup:

export const appRoutes = [
    {path: 'store', component: StoreLayoutComponent,
     loadChildren: () => import('app/store/child.module').then(m => m.ChildModule)}];

@NgModule({
    imports: [
    ...
    RouterModule.forRoot(appRoutes)
    ],
    ...})
export class AppModule {}

Surprisingly, both URLs

https://localhost:4200/store/dashboard
and https://localhost:4200/dashboard successfully load the DashboardComponent.

This behavior raises a question - why does the second URL work when it shouldn't be valid?

Answer №1

The issue arose from the inclusion of the StoreModule in both the lazy loading setup and the app.module.ts. This resulted in duplicate routing for the module, one as a direct child of the app.module and another as a lazy loaded module at the correct path.

By removing the import declaration of StoreModule from the app.module.ts, the problem was successfully resolved.

This solution may prove beneficial to others facing a similar challenge in the future.

Answer №2

For a better structure, consider placing the child routes within the children property.

Child Routes

@NgModule({
    declarations: [DashboardComponent],
    imports: [RouterModule.forChild(childRoutes)]})
export class ChildModule{}

export const childRoutes = [{
children:[
    {path: 'dashboard', component: DashboardComponent},
    {path: 'reports', component: ReportsComponent}]
}];

Parent Route

export const appRoutes = [
    {path: 'store', component: StoreLayoutComponent,
     loadChildren: () => import('app/store/child.module').then(m => m.ChildModule)}];

@NgModule({
    imports: [
    ...
    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

Using npm and systemjs as a build tool in an Angular 2 app (RC 5): A step-by-step guide

While I am well-versed in using gulp and systemjs for bundling applications (such as utilizing compression, bundling, exporting to build folder, etc), my boss now requires just npm and systemjs to complete the task. I am unsure of how to create a custom sc ...

Using Angular and Angular Material to project content within MatDialog.open()

Suppose I have a Component: @Component( selector: "demo-comp", template: ` <div> Some text... <ng-content></ng-content> </div> ` ) export class DemoComponent { constructor(public dialogRef: MatD ...

The version of the replication configuration schema does not support the use of ReplicationTime

I am currently working on setting up S3 Replication using the AWS CDK. I have referenced https://github.com/rogerchi/cdk-s3-bucketreplication/blob/main/src/index.ts as a starting point, and while it does create a replication rule, I am facing some issues c ...

The Angular CLI encounters issues when attempting to download Angular 6 dependencies through a proxy server

I have successfully set up Angular CLI using NPM behind a proxy with Fiddler. However, I am encountering an issue when trying to use the 'ng new' command with Angular CLI. It consistently fails to download certain dependencies and gives me an E50 ...

Error with Typescript types when using Styled Components

After successfully setting up styled-components in react-native, I encountered an issue while trying to use it in a simple example with react-native-web: import * as React from 'react'; import styled from 'styled-components'; export d ...

Utilizing HTML imports in Typescript for efficient use as TemplateStringLiteral

Recently, I started using TypeScript for the first time and I'm looking to integrate it into my webpack build. Currently, I am working with ts-loader and babel-loader to load TypeScript files while also attempting to include HTML files within the scr ...

synchronize the exchange of information and events between two components

Just joined this platform and diving into Angular 7 coding, but already facing an issue. I've set up two components along with a service. The data is fetched by the service upon clicking a button in the searchbar component, and I aim to display it i ...

Having trouble with importing ResizeSensor library into typescript

In my TypeScript app using webpack, I am attempting to utilize css-element-queries/ResizeSensor. After adding the npm package, which includes a .d.ts file, I encountered an issue when writing the following code: new ResizeSensor(element, cb); Instead of ...

Guide to generating TypeScript output files within a non-hierarchical directory layout

In my project, I have a directory structure with multiple typescript files organized as follows: | src | app-1 | tsconfig.json | app-2 | tsconfig.json | common | standalone | tsconfig.json For each of the ...

How can I configure Material-UI's textfield to return a numerical value instead of a string when the type is set to "number"?

Utilizing Material-UI's TextField alongside react-hook-form to monitor inputs has raised an issue for me. I have observed that regardless of the input type, it always returns a string. This creates conflicts with the data types I am using in my codeba ...

Unable to locate image on Angular server while running on Raspberry Pi

After setting up my Raspberry pi using Angular to create a simple website with the basic ng serve command, I encountered an issue when trying to add my own image. When I attempt to use src to link to my image file, it is not being found: <img src="air. ...

Converting JSON to string in Typescript is causing an error where type string cannot be assigned to type '{ .. }'

Here's the code snippet I'm working with: interface ISource extends IdModel { source_type_id: number; network_id: number; company_connection_id: number; feed_id: number; connection_id: number; feed_ids: number[]; name: string; tag ...

What is the proper method for utilizing a conditional header in an rtk query?

How can I implement conditional header authentication using rtk query? I need to pass headers for all requests except refresh token, where headers should be empty. Is it possible to achieve this by setting a condition or using two separate fetchBaseQuery ...

Move your cursor over a specific element to trigger an effect on another element that is not directly next to or related to it

In my current project, which is built with Angular, I am looking for a way to achieve a specific effect without using jQuery. Specifically, I would like the text inside a div element with the class title to have underline styling when hovering over an im ...

When initializing an object, TypeScript automatically converts numbers to strings

I am working on a function that generates a POST request from class properties, but I have encountered an issue with data types. Here's the code snippet: public state: number; updateField(field: string | number, name: string, team: boolean = true) ...

The formBuilder validator pattern seems to be malfunctioning

I am attempting to display a message when the password does not meet the formGroup pattern. Here is how my FormGroup is initialized: this.signupForm = fb.group({ userName: ['', Validators.compose([Validators.required,Validators.pattern(/^&bsol ...

Ensure that a string contains only one instance of a specific substring

I need a function that removes all instances of a specific substring from a string, except for the first one. For example: function keepFirst(str, substr) { ... } keepFirst("This $ is some text $.", "$"); The expected result should be: This $ is some tex ...

Issue: Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables like Arrays. Solution needed to resolve this

Code snippet for a service that returns JSON data export class EmployeeServiceService { constructor(private _http:Http) { } GetEmployees(): Observable<IEmployee[]>{ debugger; return this._http.get("http://localhost:2724/a ...

Setting up the newest version of Angular (v15) along with Bootstrap (v5) using .scss files

What is the process for integrating Angular with bootstrap and SASS (.scss files)? ...

Implementing an interface with a variable key and defining the key simultaneously

I am trying to design an interface with a fixed key, as well as a variable key, like this : interface Data { api?: { isReady: boolean; }; [key: string]: string; } This setup gives me the following error message : Property 'api' of typ ...