Angular 5: Utilizing distinct router-outlets in separate modules for optimized lazy loading experience

Having two modules with routing module files and router-outlets in their html, I aim to load components based on the current module.

The file tree structure is as follows:

project
|-- module2
|-- -- profil
|-- -- - profil.component.html 
|-- -- - profil.component.ts
|-- -- - profil.component.spec.ts
|-- -- - profil.component.css
|-- -- module2-routing.module.ts
|- module1-routing.module.ts
|- module1.module.ts
|- module1.component.ts
|- module1.component.spec.ts
|- module1.component.css

The relevant files are:

module1-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
    { path: '', redirectTo: '/home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent },
    { path: 'module2', loadChildren: './module2/module2.module#Module2Module' }
];

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

module1.component.html

<router-outlet name="m1"></router-outlet>

module2-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from './home/home.component';
import { ProfilComponent } from './profil/profil.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'profil', component: ProfilComponent }
];

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

module2/home.component.html

<div id="module2-home">

  <app-header></app-header>
  <router-outlet name='m2'></router-outlet>

</div>

Setting the outlet option (example: { path: 'profil', component: ProfilComponent, outlet: 'm2' } ) in my routing files triggered this error :

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'home'
Error: Cannot match any routes. URL Segment: 'home'

Answer №1

// In my appRouting-routing.module.ts file, I have defined the routes for my Angular application:
        const routes: Routes = [
      { path: '', redirectTo: '/login', pathMatch: 'full' },
      { path: 'login', component: LoginComponent },
      { path: 'dashboard', component: DashboardComponent },
      {
        path: 'modules', component: ModulesComponent,
        children: [
          { path: 'module1', component: Module1Component, children: Module1_ROUTE },
          { path: 'module2', component: Module2Component, children: Module2_ROUTE }
        ]
      }
    ];


    // To properly set up child routes for module1 and module2, export them from their respective routing files.
    // Here is an example of how to do it:
   export const Module1_ROUTE: Routes = [
        { path: '', redirectTo: '/home', pathMatch: 'full' },
        { path: 'home', component: HomeComponent }
    ];

For more information on setting up child routes in Angular, you can refer to the documentation. This should help resolve any issues you may encounter.

Answer №2

To ensure clarity and organization in your application, it is recommended to include your module name in the path for each route to avoid any ambiguity. This way, you can guarantee that no two routes will have the same path, ultimately resolving any potential conflicts. For more information on this topic, you can refer to the following link: Angular 2 Different modules same routing

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

Recursive type analysis indicates that the instantiation of the type is excessively deep and may lead to potential infinite loops

In the process of developing a Jest utility, I have created a solution where an object mock is lazily generated as properties are accessed or called. Essentially, when a property is invoked like a method, it will utilize a jest.fn() for that specific path ...

What are the steps for incorporating a Zoom & Pan feature into an anyChart SeatMap?

In our IONIC application, we are utilizing the anyChart SeatMap to display SVG-based seatmaps. However, some of the seatmaps are quite large and we require support for zooming and panning functionalities. Despite researching the 'Move & Zoom' opt ...

Troubleshooting problems with Angular 2 reactive forms

I am looking for help with Angular 2 reactive forms. I have two specific goals for my reactive form view: To set a default value in the dropdown menu for country name. To update the country code input field based on the selected country name. See the ...

Discovering the parameter unions in Typescript has revolutionized the way

My current interface features overloaded functions in a specific format: export interface IEvents { method(): boolean; on(name: 'eventName1', listener: (obj: SomeType) => void): void; on(name: 'eventName2', listener: (obj: Som ...

Using Node.js with Typescript and RedisJSON allows for a powerful and efficient

I've recently started delving into nodejs, typescript, and redis for programming. However, I've encountered an issue with redis: when defining a data interface to be stored in redis, the system throws errors as soon as I try to specify the data t ...

Using Angular's CanDeactivateGuard with Child Components in Angular4

Ensuring user awareness of unsaved changes when navigating away from a page is crucial. Previously, I achieved this in angular 1 using the ng-unsaved changes plugin. However, in angular 4, it seems recommended to utilize the canDeactivate feature. This wor ...

Combine and transform multiple hierarchical JSONs into a new format

I'm facing a challenge where I need to merge two JSON objects and convert them into a different format using TypeScript in a React project. Initially, I tried implementing this with a recursive function as well as a reducer, but unfortunately, it didn ...

Is there a way to use WithStyles<typeof styles> within Material UI?

import { WithStyles, createStyles } from '@material-ui/core'; const styles = (theme: Theme) => createStyles({ root: { /* ... */ }, paper: { /* ... */ }, button: { /* ... */ }, }); interface Props extends WithStyles<typeof styles> ...

What is the best way to display the loan detail and credit detail tables beneath the application detail section that is currently blank?

I have a total of four tables on my page. The size of one table is almost identical to the other three smaller tables. I am looking to place the loan details and credit details table below the application detail, in a way that utilizes the empty space avai ...

I have a data.json file with a URL that I need to access in my view using Angular. How can I achieve this without relying on innerHTML?

Here is the JSON file data.json that I am referring to: { "id": 1, "title": "POC", "desc": "<a href='www.google.com'>HOMEPAGE</a>", "status": "done", "percentage_finished": 100 } I am tryi ...

RTK Query - executing a query upon mounting with lazy loading enabled

Should rerendering be triggered by sending a request on mount? Or is the use of useEffect necessary? (Is lazy mode different from regular queries?) export const Catalog: React.FC<CatalogProps> = ({ object, category }) => { const [getCatalogPro ...

How can we use the Vertx router in Quarkus to automatically redirect all unknown routes to index.html?

I have a unique setup with my Quarkus application where I package an Angular SPA within the JAR file. The backend API routes are provided by Quarkus for the front end to consume. During the build process of the Quarkus application, the Angular application ...

Listening for successful operations in ngrx can be done by following these steps

My Angular2 application utilizes ngrx Store and Effects successfully. However, I am unsure of the optimal approach to handle determining when a service call operation has finished successfully in order to update the view with a success alert or similar mes ...

Showing off the latest products at the top of the list

Typically, when utilizing ngFor, the most recent item is displayed underneath the initial element. For instance, a list containing: [Apple, Orange, Banana] If we use ngFor to display this list: Apple Orange Banana I am interested in learning a method t ...

Adjust the size of the mat-expansion indicator to your desired height and width

Trying to modify the width and height of the mat indicator has been a bit challenging. Despite following suggestions from other similar questions, such as adjusting the border width and padding, I am still unable to see the changes reflect in my CSS file ...

Is there a way to deactivate the spin buttons for an input number field?

Is there a way to create an input element with type number in Vue using createElement() in TypeScript and then disable the spin buttons for increment and decrement? I attempted to use the following CSS: input[type=number]::-webkit-inner-spin-button, input ...

Backend data not displaying on HTML page

I am currently working on an Angular 8 application where I have a service dedicated to fetching courses from an API endpoint. The service method that I'm using looks like this: loadCourseById(courseId: number) { return this.http.get<Cours ...

The use of credentials is not allowed when the ‘Access-Control-Allow-Origin’ CORS header is set to ‘*’

My Java web application makes CORS requests where the browser performs an OPTIONS preflight before the actual request. The format of each request is as follows: Host: localhost:8080 User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/2 ...

Specialized Character Formats in TypeScript

In my quest to enhance the clarity in distinguishing different types of strings within my program - such as absolute paths and relative paths, I am seeking a solution that ensures functions can only take or return specific types without errors. Consider t ...

The child user interface component is failing to respond to keypress events within the parent component in an Angular project

I am facing a challenge in adding a keyboard shortcut to open a nested child UI Tab component through a keypress event. However, the Child nested tab can only be loaded after the Parent component is loaded first. Below is the structure of the UI tree: |-- ...