Guide on merging paths in distinct modules within an Angular project

I am looking to merge two sets of routes from different modules in my application.

The first module is located at:

./app-routing.module.ts

import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {UserDashboardComponent} from './user-dashboard/containers/user-dashboard/user-dashboard.component';
import {NotFoundComponent} from './not-found/not-found.component';

const ROUTES: Routes = [
  { path: '', component: UserDashboardComponent, pathMatch: 'full' },
  { path: '**', component: NotFoundComponent, pathMatch: 'full' },
];

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

And the second module is located at:

./auth.module.ts

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {RouterModule, Routes} from '@angular/router';
import {LoginComponent} from './login/containers/login-view/login-view.component';
import {RegisterComponent} from './register/containers/register-view/register-view.component';

export const ROUTES: Routes = [
  {
    path: 'auth',
    children: [
      { path: '', pathMatch: 'full', redirectTo: 'login' },
      { path: 'login', component: LoginComponent },
      { path: 'register', component: RegisterComponent },
    ],
  },
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forRoot(ROUTES)
  ],
})
export class AuthModule {}

The part where these two should converge is at:

./app.module.ts

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

import {AuthModule} from '../auth/auth.module';

import {AppRoutingModule} from './app-routing.module';
import {UserDashboardModule} from './user-dashboard/user-dashboard.module';

import {AppComponent} from './app.component';
import {NotFoundComponent} from './not-found/not-found.component';

@NgModule({
  declarations: [
    AppComponent,
    NotFoundComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule, // main routes
    AuthModule, // authorization module which also has routes
    UserDashboardModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
  exports: [NotFoundComponent],
})
export class AppModule {}

In my app.component.ts file:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div class="app">
      <router-outlet></router-outlet>
    </div>
  `,
})

export class AppComponent {}

Currently, I am only able to see the routes from 'app-routing.module.ts'. How can I also utilize the routes from auth?

Answer №1

To implement in ./auth.module.ts, experiment with utilizing

RouterModule.forChild(ROUTES) 

in place of

RouterModule.forRoot(ROUTES)

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

Assign a value to a FormControl in Angular 6

I have 60 properties linked to 60 controls through the mat-tab in a form. When it comes to editing mode, I need to assign values to all the controls. One approach is as follows: this.form.controls['dept'].setValue(selected.id); This involves l ...

Stop extra properties from being added to the return type of a callback function in TypeScript

Imagine having an interface called Foo and a function named bar that accepts a callback returning a Foo. interface Foo { foo: string; } function bar(callback: () => Foo): Foo { return callback(); } Upon calling this function, if additional pr ...

Is it possible to modify the host header within an Angular app?

I'm experiencing a vulnerability issue and to resolve it, I need to utilize SERVER_NAME instead of the Host header. Is it possible to accomplish this using Angular? ...

Limiting the use of the Tab key within a modal dialog box

Currently, I have implemented a modal window that appears when a .btn link is clicked. However, I am facing an issue where users can still navigate through links and buttons in the background by pressing the Tab key. This becomes problematic especially fo ...

Accessing dynamically inserted child components in Angular 2.0

Currently, I am utilizing this sample to dynamically generate components within my application. export class App { @ViewChild('placeholder', {read: ViewContainerRef}) viewContainerRef; private componentFactory: ComponentFactory<any> ...

The loginError variable in the ts file may experience a delay in updating its value

After entering an incorrect email and password, clicking on submit should set this.LoginError to return true in the component ts file console. However, it initially returns false, and only after clicking submit two or three times does the value finally upd ...

When the page is first loaded, the select options dropdown using NgFor and NgValue does not display the initial object from the list

I am facing an issue with a select options dropdown that contains a list of objects. I have used ngValue to set the value of the dropdown as an object. However, upon page load, the dropdown does not display the first object from the list; it only shows obj ...

In the context of Angular, the ELSE statement continues to run even after the IF condition has been satisfied within

Currently, I am utilizing Angular 11 in conjunction with Firestore. Within my code, I am fetching data using the subscribe method from an API service. Subsequently, I am employing a for loop to extract object values in order to verify if a value within a c ...

Assign Monday as the selected day of the week in the MUI Datepicker 6

I am currently using version 6 of the material ui Datepicker and I am trying to configure it so that the week starts on Monday. import React from "react"; import { DatePicker as DatePickerDestop } from "@mui/x-date-pickers/DatePicker"; ...

Creating a Typescript mixin function that accepts a generic type from the main class

I am working with the code snippet shown below: // Types found on https://stackoverflow.com/a/55468194 type Constructor<T = {}> = new (...args: any[]) => T; /* turns A | B | C into A & B & C */ type UnionToIntersection<U> = (U extend ...

Utilizing type guards in prop functions for conditional rendering within React TypeScript adds an extra layer

In my code, I am conditionally rendering a Button. However, I encountered an issue on line 7 where TypeScript is indicating that the first parameter of the exportExcel function may be null even though it should not be, considering the conditional render lo ...

I've tried using a ControlValueAccessor, but for some reason the value isn't getting passed to the form

Currently, I am experimenting with reactive forms in Angular, and I'm encountering difficulties with updating the form from custom components. As an example, take a look at the date-input component created using flatpickr in the linked Plunker demo. ...

The program abruptly shut down with error code 127. Any idea why this occurred?

I'm having issues while attempting to create an app from a script. When I run "ionic serve," the following errors occur: [error] Error: Job name "..getProjectMetadata" does not exist. at Observable._subscribe (C:\Users\Bhanu\Desktop&bs ...

What is a way to merge all the letters from every console.log result together?

I'm encountering an issue - I've been attempting to retrieve a string that provides a link to the current user's profile picture. However, when I use console.log(), the output appears as follows: Console Output: https://i.sstatic.net/70W6Q ...

To use the ModuleWithProviders<T> in the angular-autofocus-fix package, you must provide 1 type argument

Upon successful installation of angular-autofocus-fix I have imported the AutofocusModule However, upon running the Angular project, I encountered the following error: ERROR in node_modules/angular-autofocus-fix/index.d.ts:4:23 - error TS2314: Generic ty ...

Angular displays error ERR_UNKNOWN_URL_SCHEME when attempting to retrieve an image saved in a blob

As I transition my app from Electron to Angular, one of my main objectives is to display an image uploaded by a user. Here's how I attempted to achieve this: page.component.ts uploadImageFile(){ fileDialog({}, files =>{ //Utilizing the fileDi ...

What makes TypeScript believe that the variable could possibly be undefined when it is clearly not the case?

I recently encountered an issue where TypeScript incorrectly identifies a variable as possibly being undefined. Here is a simplified example: const func = (val1?: boolean, val2?: boolean) => { if (!val1 && !val2) return; let result: boolean; ...

Set up Admin SDK using appropriate credentials for the given environment

As someone new to Node.js, Firebase Cloud Functions, and TypeScript, my objective is to create a cloud function that acts as an HTTP endpoint for clients to authenticate with Firebase. The desired outcome is for the cloud function to provide a custom acces ...

Having trouble utilizing datepipe with locale format

Currently, I'm constructing a website using angular2 final alongside webpack cli. One of my specific requirements is to showcase the date in the nl-NL locale. The html code snippet that I have written for this purpose looks like: {{eventDate | date:& ...

Angular `CORS` Ailment

I am currently utilizing the MEAN stack (MongoDB, Express, Angular, and NodeJS). I have a basic function for fetching data from an external API as shown below: let api = 'https://thongtindoanhnghiep.co/api/city'; return this.http.get<any>(a ...