Exploring the concept of relative routing within Angular

Update

I made the switch from forRoot to forChild based on the responses received.

Essentially, I have two issues to address. Let's consider this as a submodule:

@NgModule({
  imports: [
    CommonModule,
    ARoutingModule,
    BModule
  ],
  declarations: [AppsComponent, ...],
  exports: [
    AppsComponent, ...
  ]
})
export class AModule { }

and

@NgModule({
  imports: [
    CommonModule,
    BRoutingModule
  ],
  declarations: [AppsComponent, ...],
  exports: [
    AppsComponent, ...
  ]
})
export class BModule { }

Hence, AModule is imported by the root module, and both modules, AModule and BModule, are required to define their own routes. For instance,

// ./A/A-Routing.module.ts
const routes: Routes = [
  {
   path: 'A',
   component: AComponent
  }
  ];

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

Additionally, in the subsub section we have

// ./A/B/B-Routing.module.ts
const routes: Routes = [
  {
   path: 'B',
   component: BComponent,

   ]
  }
  ];

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

Is it viable to achieve this? Utilizing a path printing tool, I can access the sub-routes but not the subsub routes (i.e., B). Can I establish the routes in B without prior information about the preceding path? In other words, defining route for else without knowledge of something?

If interested, you can view an example using Stackblitz here. While main functions properly, the Subs encounter difficulties...

Answer №1

To get everything working properly, there are a few adjustments you'll need to make.

  1. First, ensure you set up an initial route for your SubModule as a Lazy Loaded Module. This step can be done in your main-routing.module.ts file.

const routes: Routes = [
  {
    path: 'main',
    component: MainComponent,
    children: [{
      path: 'sub',
      loadChildren: './sub/sub.module#SubModule'
    }]
  }
];
  1. Next, create a module called SubModule and use the SubRoutingModule to handle routing within this module. Don't forget to declare Sub1Component and Sub2Component inside:

import { Sub1Component, Sub2Component } from './sub.component';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { SubRoutingModule } from './sub-routing.module';

@NgModule({
  declarations: [Sub1Component, Sub2Component],
  imports: [SubRoutingModule]
})
export class SubModule { }

Your updated routes should now look like this:

<a routerLink="/main/sub/sub1">Sub1</a> | 
<a routerLink="/main/sub/sub2">Sub2</a>

Check out this Revised StackBlitz for reference.

Answer №2

Update forRoot to forChild within the SubSubRoutingModule

// ./Sub/subsub/SubSub-Routing.module.ts
const routes: Routes = [
  {
   path: 'subsub', //<-- This will direct to www.site.com/sub/subsub
   component: SubSubComponent,
   ]
  }
 ];

@NgModule({
  imports: [RouterModule.forChild(routes)], //<-- Make change here
  exports: [RouterModule],
  declarations: []
})
export class SubSubRoutingModule { }

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

How to identify the type of a union type in Typescript

I am curious about the type c used in the printTypeOf function. Check out my code below: type Email ={ email:string, } type Phone ={ phone:string, } type ContactInfo = Email | Phone; function printTypeOf(c: ContactInfo) { console.log(typeof c ...

Feeling perplexed about distinguishing between Modules and Components in Angular 2

Hey everyone, I'm just starting out with Angular2 and I have a question about the concepts of @NgModule and @Component: Are they completely different in terms of concept, or are they similar with the main difference being that @NgModule acts more li ...

Manipulate MySQL data in Node.js by storing it in a variable

Struggling to grasp the concepts of nodeJS/typescript and how to effectively save database query results into variables for return. Seeking assistance to solve the problem faced: Here is a method snippet that needs help: public getAllProducts(): ProductA ...

Typescript - Creating a Class with Constructor that Extends an Interface without Constructor

I am faced with an interface structured as follows: interface Person { id: number name: string } In my implementation class for this interface, I have the following code: class PersonClass implements Person { id: number = 123 name: string = &apo ...

I desire to obtain an image from a different webpage

I am a beginner in the world of Ionic/Angular. On my edit profile page (which is a separate page), I have the ability to change my profile picture. When I make this change, it should automatically reflect on my main profile page, which is on another page. ...

Tips for updating a component's state from another component in a React Native application

I have a map displaying a specific region based on the user's location. I am trying to implement a button in a separate file that will reset the map back to the user's current location while maintaining modularity. Can someone guide me on how to ...

Issue with RouterLink not recognizing QueryParams

I have encountered an issue where dynamically generated URLs with queryParams inside [routerLink] are breaking routes. For example: this.url = '/question/ask?details=1' <a [routerLink]="url"> {{ data.name }}</a> Upon mouseover, the ...

What event type should be used for handling checkbox input events in Angular?

What is the appropriate type for the event parameter? I've tried using InputEvent and HTMLInputElement, but neither seems to be working. changed(event) { //<---- event?? console.log({ checked: event.target.checked }); } Here's the com ...

Apply a specific style to the initial element generated by *ngFor

My current method for displaying a certain number of * characters is utilizing the code snippet below: <div *ngFor="let line of lines; let i=index">*</div> I am interested in applying a margin only to the first element. The margin value sh ...

Build a Google Map Widget within SurveyJs

Hey there, I'm new to working with SurveyJS and I'm trying to incorporate a Google Map widget into my SurveyJS. I followed some steps and successfully added the map in the Survey Designer section, but unfortunately, it's not loading in the T ...

Ionic (Angular) experiencing crashes due to numerous HTTP requests being made

My template contains a list of items <ion-list class="ion-text-center"> <div *ngIf="farms$ | async as farmData"> <ion-item (click)="selectFarm(farm)" *ngFor="let farm of farmData" detail=&quo ...

Angular: Automatically close the side navigation menu when a user clicks anywhere outside of it in the screen

My current issue involves using a sidenav library where I need to close the sidenav when the user clicks anywhere on the screen. Despite several attempts, I have been unable to make it work successfully. Below is the code snippet in question: html < ...

Using Angular's asterisk wildcard to correctly match nested routes

Struggling to locate subroutes using a component const routes: Routes = [ { path: '', component: CatalogueComponent, }, { path: 'search/**', component: CatalogueComponent, }, ... { path: '**', ...

Implementing Dynamic Columns and Rows in GridLayout using NativeScript

My HTML code consists of two GridDatas and two buttons. When Button1 is pressed, gridData1 should be displayed, and when Button2 is pressed, gridData2 should be displayed. The number of rows and columns remains static. Here are the TypeScript snippets: g ...

Elevating font-awesome from version 4.7 to 5.11.1 in an Angular 6 project

Currently in my angular 6 project, the parent module utilizes font-awesome 4.7 as shown in package.json; "font-awesome": "^4.7.0", and angular.json; "styles": ["projects/adminUI/src/styles.css", "./no ...

Angular is showing an error indicating that the property "name" is not found on an empty object

After thorough checking, I have confirmed that the property does exist with the correct key. However, it is returning an error message stating name is not a property of {}. I attempted to assign this object to an interface along with its properties but enc ...

Creating a generic hashmap that can accept dynamic keys and an array of type T

In my attempt to create a robust typing interface for a hashmap in typescript, The hashmap consists of a key with a dynamic string name, and a values array containing a Generic type. I attempted to define the interface as follows: export interfa ...

Avoiding repeated observable executions

My current task involves implementing a screen that displays constantly changing data from an API. To achieve this, I have utilized the repeatWhen() method on the observable generated by the API call for polling purposes. Additionally, I need to make an ex ...

What is the process for extracting dates in JavaScript?

I need help extracting the proper date value from a long date string. Here is the initial date: Sun Aug 30 2020 00:00:00 GMT+0200 (Central European Summer Time) How can I parse this date to: 2020-08-30? Additionally, I have another scenario: Tue Aug 25 ...

"Ionic2 makes an HTTP POST request and then follows up with an

I've been attempting to post data using the Angular HTTP POST method as shown below. However, it seems to be executing the GET method instead. Any advice or guidance on this issue would be greatly appreciated. https://i.stack.imgur.com/IkSq3.png log ...