Navigating within a Module in Angular

[enter image description here][1][I am facing an issue with lazy loading the user module in my application. I have set up a login page as the default path in the user.routing file, but for some reason, I cannot navigate from the login page to the signup page using router.navigate. The User module consists of sub-modules (login, signup, forgot) which are components within the user module. Interestingly, everything works perfectly fine when I import the User Module in the App Module. However, if I do not import the User Module in the App Module, the routing functionality along with other directives does not work as expected.]

App Structure:
app
|-(appModule.ts, app.component.ts, app.component.html)
|-user
   |-[UserModule.ts, user-routing.ts]
   |-loginComponent
   |-signupComponent
   |-forgotComponent

UserModule:
const routes: Routes = [     
         { path: '', component: LoginComponent },     
         { path: 'signup', pathMatch:'full',component: SignupComponent },    
         { path: 'forgot', component: ForgotComponent } 
];
@NgModule({
  declarations: [LoginComponent, SignupComponent, ForgotComponent],
  imports: [
    CommonModule,
    RouterModule.forChild(routes),
  ]
})

AppRouting:
export const routes: Routes = [   
{ path: 'login', pathMatch: 'full' ,loadChildren: () => import('./user/user.module').then(m => m.UserModule)},

 ]

Answer №1

Check out the live demo

If you're considering lazy loading the user module, I recommend implementing a routing component:

@Component({
  selector: `user-routing-component`,
  template: `<router-outlet></router-outlet>`
})
export class UserRoutingComponent {}

With the following setup:

@NgModule({
  imports: [
    RouterModule.forChild([
      {
        path: '',
        component: UserRoutingComponent,
        children: [
          {
            path: '',
            component: LoginComponent,
            pathMatch: 'full'
          },
          {
            path: 'signup',
            component: SignupComponent
          },
          {
            path: 'forgot',
            component: ForgotComponent
          }
        ]
      }
    ])
  ], // imports,
  declarations: [
    UserRoutingComponent, 
    LoginComponent,
    SignupComponent,
    ForgotComponent
  ],
  exports: [RouterModule]
})
export class UserModule {}

Define the parent route like so:

RouterModule.forRoot([
  {
    path: 'login',
    loadChildren: () => import('PATH/TO/USER/MODULE/user.module')
        .then(m => m.UserModule)
  }
])

After implementation, your routes will be:

  • login
  • login/forgot
  • login/signup

Perhaps consider changing them to:

  • auth/login
  • auth/forgot
  • auth/signup

What do you think of this restructuring?

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

Where is the best place to import styles in NextJS?

I have an existing project with a file importing the following function import theme from 'src/configs/theme' However, when I created a new Next.js project and replicated the same folder structure and imported the same function, it is showing "m ...

Error encountered: Mongoosastic search doesn't work properly in TypeScript environment

Currently, my setup involves using mongoose v6.0.0, mongoosastic v5.0.0, and integrating typescript. However, even after initializing the plugin and attempting to correctly set the types, I am encountering issues where functions like PageModel.search intro ...

Uploading files into an array using Angular 2

Struggling to incorporate an uploader within an array: I've got an array of users displayed in a table using "ng-repeat". I want to add a column with a button to upload an image for each user. Currently, I'm utilizing ng2-file-upload, but open t ...

How do I modify a response within a subscribe in Angular?

Having a scenario where multiple components are utilizing a function that expects an array of objects to be returned. However, there is one specific case where I need to modify the array based on the return value from an observable before returning it: let ...

Is there a way to determine the number of code lines in all TypeScript files by utilizing tslint?

Looking to retrieve line count of code in all .ts files using tslint? Is there a way to obtain the total line count of code in all .ts files with the help of tslint? I haven't been able to find any information about this feature in the ...

Invoking functions from an array of TypeScript union types

Within my Typescript array, I have two classes: StripeCardModel | StripeBankModel Both of these classes extend StripePaymentModel My goal is to locate a specific class within the array that can potentially contain instances of both classes. Once found ...

Is it necessary to have a premium firebase/firestore account in order to set up stripe payments?

When learning how to integrate Stripe payments with Angular and Firebase, make note that a paid Firebase account is required for the cloud function to work. External API requests are blocked on the free "Spark" plan. ...

Is subtyping causing issues in TypeScript's inheritance model?

I am currently utilizing TypeScript for my coding projects, and I have observed that it can allow the production of non-type-safe code. Despite implementing all the "strict" options available to me, the behavior I am experiencing goes against the principle ...

Tips for assigning a JSON object as the resolve value and enabling autosuggestion when utilizing the promise function

Is there a way to make my promise function auto-suggest the resolved value if it's a JSON object, similar to how the axios NPM module does? Here is an example of how axios accomplishes this: axios.get("url.com") .then((res) => { Here, axios will ...

forEach was unable to determine the appropriate data types

define function a(param: number): number; define function b(param: string): string; define function c(param: boolean): boolean; type GeneralHooks<H extends (...args: any[]) => any> = [H, Parameters<H>] const obj = { a: [a, [1]] as Gene ...

Custom Joi middleware in Express v4 is failing to pass the Request, Response, and Next objects

I am currently in the process of developing a unique middleware function to work with Joi that will be placed on my routes for validating a Joi schema. In the past, I have created middlewares for JWT validation without passing any parameters, and they wor ...

Learn how to enhance a Vue component by adding extra properties while having Typescript support in Vue 3

Attempting to enhance a Vue component from PrimeVue, I aim to introduce extra props while preserving the original components' typings and merging them with my new props. For example, when dealing with the Button component that requires "label" to be ...

What is the best way to transfer login information to the next stage in Angular 4?

I am currently developing a project in Angular 4 and have encountered an issue with passing login information to the next state upon successfully changing states. In AngularJS, we could achieve this using stateParams, but I'm unsure of how to implemen ...

RxJS: Understanding the issue of 'this' being undefined when used within the subscribe method

As I work on setting up a simple error notifications component and debug in Visual Studio, an issue arises within the subscribe function where 'this' is undefined. public notifications: NotificationMessage[]; constructor(notificationService: N ...

Refreshing/reloading Angular 9 SSR pages

Encountering an issue with Angular and SSR. Running angular 9, everything runs smoothly except when I refresh the page (F5), it first displays the login page before loading the current page. Previously built with angular 8, where this problem did not occur ...

Switching a react virtualized table from JavaScript to TypeScript can uncover some type-related challenges

I have implemented the following demo in my React project: https://codesandbox.io/s/react-virtualized-table-checbox-stackoverflow-rbl0v?fontsize=14&hidenavigation=1&theme=dark&file=/src/App.js However, I am encountering issues with the code sni ...

Using Angular 2 to Toggle a Checkbox when a Div is Clicked

Whenever a user clicks on a unit div, I want to target the checkbox and mark it as checked/unchecked. I also want to apply the class unit-selected if the checkbox is checked, and remove the class unit-selected if the checkbox is unchecked. I have tried lo ...

Navigating through nested routes in Angular 5

I recently started learning about Angular, and I could really use some guidance on routing. Here is my current setup. app.component.html <router-outlet name="nav"></router-outlet> <router-outlet name="left-sidebar"></router-outlet> ...

Refresh an Angular page automatically

Having a small issue in my angular application. The problem arises on the first page where I display a table listing all employees along with a "Create New Employee" button that opens a form for adding a new employee. However, after submitting the form and ...

Using Jasmine to Jest: Mocking Nested function calls

I am currently working on testing my TypeScript functions with Jasmine: //AB.ts export async function A() { } export async function B() { A(); } My goal is to unit test function B by mocking out function A to see if it is called. Here is the code I h ...