Angular2: Separate router-outlets within individual modules

I am working on an Angular app that consists of multiple modules (modules A and B are lazy loaded):

MainModule, ModuleA, ModuleB

Currently, all content is loaded in the AppComponent (which has a router-outlet tag). However, I would like to restructure it so that I have:

AppComponent, ComponentA, ComponentB

Each component will now have its own router-outlet where the content for each module will be displayed. Any suggestions on how I can achieve this? Thank you.

Answer №1

Here is a simplified version of the main structure you need, consisting of 2 levels (main level with forRoot, and other modules level loaded using "Lazy loading" with forChild). Feel free to make it more complex by adding guards, nested levels, etc.

Below is an example structure (make sure to customize it with your own components):

  1. MainModule (app-module.ts)
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
 
import { AppComponent } from './components/App.component';
import { PageAComponent} from './modules/module-a/components/page-a.component';
import { PageBComponent} from './modules/module-b/components/page-b.component';
 
const routes: Routes = [
  {
    path: '',
    component: MainComponent ,
  },
  {
    path: 'patha', 
    component: PageAComponent,
    children: [{
      path: '',
      loadChildren: () => import('./modules/module-a/module-a.module').then(m => m.AModule)
    }],
    },
{
    path: 'pathb', 
    component: PageBComponent,
    children: [{
      path: '',
      loadChildren: () => import('.modules/module-b/module-b.module').then(m => m.BModule)
    }],
  {
    path: '**',
    redirectTo: '',
   },
];
 
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}
  1. AModule
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { PageAComponent } from './pages/page-a/page-a.component';
import { RegisterComponent } from './components/register/register.component';
import { LoginComponent } from './components/login/login.component';

const routes: Routes = [
  {
    path: '', // takes the "base path" defined in its parent routes (in app.module.ts)
    component: PageAComponent, 
    pathMatch: 'full', 
    children: [
      {
        path: 'login', // For instance
        component: LoginComponent,
      },
      {
        path: 'register', // For instance
        component: RegisterComponent,
      },
      {
        path: '**',
        redirectTo: 'login',
      },
    ],
  },
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [
    RouterModule
  ]
})
export class AModule { }
  1. BModule
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { PageBComponent } from './pages/page-b/page-b.component';
import { ListComponent} from './components/list/register.component';
import { EditComponent} from './components/edit/edit.component';

const routes: Routes = [
  {
    path: '', // takes the "base path" defined in its parent routes (in app.module.ts)
    component: PageBComponent, 
    pathMatch: 'full', 
    children: [
      {
        path: 'list', // For instance
        component: ListComponent,
      },
      {
        path: 'edit', // For instance
        component: EditComponent,
      },
      {
        path: '**',
        redirectTo: 'list',
      },
    ],
  },
];
 
@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [
    RouterModule
  ]
})
export class BModule { }
  1. In the AppComponent, you would have your main <router-outlet></router-outlet>

  2. Then, in PageAComponent and PageBComponent, you would only have <router-outlet></router-outlet> as well. These components act as containers for child module components.

These are the basic structures you can use, but feel free to modify the names of components, paths, and modules to fit your specific needs.

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

What is preventing Ionic from locating my model interface?

I recently started working with Ionic and I am using a tutorial as a guide to integrate Firebase authentication into my project. However, I am encountering an issue with the user interface that is being generated. When I run ionic serve for the first time ...

Ways to collect particular tokens for delivering targeted push notifications to designated devices

When filtering the user's contacts, I ensure that only contacts with created accounts are displayed on the screen. This process helps in visually organizing the contact list. List<PhonesContacts> phoneContacts = snapshot.data; Lis ...

Initiating a GET request to execute an SQL query with specified parameters

Let me provide some background information. I am currently using Angular for the frontend and Express for the backend, while also learning how to effectively utilize both technologies. In my application, there is a parent component that generates a group ...

Is it possible for the button text to switch from Farewell to Greetings after two clicks?

There seems to be a strange issue in my React TS project - I have to click the button twice to switch the text from "Goodbye" to "Hello", but not the other way around. Any ideas why? import { useState } from 'react' const ChangeTextButton = () ...

Exploring/Adjusting an RxJS Observable Object

I'm currently working with a typescript method that looks like this: private processRequest<T>(request: Observable<T>, ...): Promise<T> {...} request is an HttpClient Observable processRequest(httpClient.get(url, ...)); ... processR ...

Error in Angular 7: params.map function is undefined

When attempting to launch my Angular 7 application with ng serve, I suddenly encountered the following error: ERROR in params.map is not a function I am unsure of the origin of this error as ng isn't providing much information. I have attempted to ...

Angular project hosting causing malfunctions in route parameters

Encountering a problem with route parameters after deploying my website on namecheap hosting. Routes Setup: const routes: Routes = [ { path: 'women', component: ProductlistingComponent }, { path: 'women/:search_1', component: ...

Revving up the RxJS Engine: Unleashing the Potential of race

I'm currently working on implementing a unique input component that will execute a search when either the input value changes (with a debounce of 500ms) or when the enter key is pressed. My goal is to avoid emitting the search term twice - once on the ...

Using FontAwesome with Angular: difficulty in styling paths

I recently completed a new project and decided to enhance it by incorporating font-awesome icons: "@fortawesome/angular-fontawesome": "^0.4.0", "@fortawesome/fontawesome-svg-core": "^1.2.19", "@fortawesome/free-brands-svg-icons": "^5.9.0", After installi ...

Filter through the array of objects using the title key

I'm attempting to extract specific data by filtering the 'page_title' key. Below is a snippet of my JSON object: { "page_components": [ { "page_title": "My Account", "row_block": [ { "heading": "", "sub_headi ...

Parent Component in Angular 2 Fails to Refresh Upon Observable Update

I have been utilizing an Observable service to facilitate data coordination among components. Specifically, I am attempting to utilize it for managing the visibility of various HTML elements within my application. Currently, when I toggle the behavior sub ...

The compatibility between jQuery serialize and Angular Material tabs is not optimal

Can anyone help with an issue I'm facing? I have angular material tabs embedded within a form tag, and you can view my code example here. The problem arises when I attempt to serialize the form using jQuery in my submit function: submit(f: HTMLElemen ...

Extracting the "defined" type from a TypeScript property during runtime

My current task Presently, I am iterating through the keys of an object and transferring their values to another object. interface From { [key: string]: string; } let from: From = { prop1: "foo", prop2: "23", }; interface To { [key: str ...

When Angular site consumes a URL with parameters including an email hyperlink, the email address is being automatically rendered in lowercase

Hey there! I am currently working on a project that involves dotnetcore2 and angular. As part of the process, I am using Core functions like UserManager to generate a token called GeneratePasswordResetTokenAsync(). This token is then sent to the user via ...

Is it possible to configure a custom timezone for the Angular Material datepicker feature?

I am currently working on an Angular 7 application and I have encountered a challenge with the date field. In this particular field, I am utilizing the Angular Material Datepicker input. However, I have noticed that the datepicker automatically captures th ...

When utilizing the navigation.navigate function, react-navigation v6.0 may present an error message

The Challenge I'm Dealing With One issue I encountered is when I use navigation.navigate('XXXPage'), react-navigation version 6.0 displays the following error message. Argument of type 'string' is not assignable to parameter of ty ...

The functionality of the dynamic drag and drop form builder is not functioning as expected in Angular 12

I am currently developing a dynamic form builder using Angular version 12. To achieve this, I decided to utilize the Angular-Formio package. After installing the package and following the steps outlined in the documentation, I encountered an issue. The i ...

Material 2's portal host fails to display the specified template portal

Check out the Demo Plunker here: https://plnkr.co/edit/Ye8MAUmrMEQKnPt93TjT?p=preview I'm following the guidance from Material 2 documentation in order to establish a template portal that will be displayed within a nearby host (although my ultimate g ...

How to implement a reusable module with distinct routes in Angular

In my current angular project, we have various menus labeled A, B, C, D, and E that all utilize the same module. Specifically, menus A, C, and E use the same component/module. My goal is to ensure that when I am on menu A and then click on menu C, the sa ...

What are the steps to integrate the TawkTo JS API into an Angular application?

I'm running into some challenges trying to implement the TawkTo JS API within my Angular application. Can anyone provide guidance on how to effectively integrate it? ...