Discover how to set up lazy loaded child routes within a parent route that is also loaded lazily in Angular 2

Struggling to implement lazy loading for my app has been a series of challenges. I successfully implemented lazy loading for the main route, /admin, but now I am facing issues while adding another route, /admin/login.

This is what I tried:

admin-router.module.ts

@NgModule({
  imports: [
    ComponentsModule,
    SharedModule,
    RouterModule.forChild([
      {
        path: '',
        component: AdminAreaComponent,
        children: [
          {
            path: 'login',
            loadChildren: 'app/+admin-area/pages/login/login.module#LoginModule'
          }
        ]
      }
    ])
  ],
  exports: [
    RouterModule
  ],
  declarations: [
    AdminAreaComponent
  ]
})
export class AdminAreaRouterModule {}

login-router.module.ts

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

// Global modules
import {ComponentsModule, SharedModule} from '../../shared';

// Components
import {LoginComponent} from '../login.component';

@NgModule({
  imports: [
    ComponentsModule,
    SharedModule,
    RouterModule.forChild([
      {
        path: '',
        component: LoginComponent
      }
    ])
  ],
  exports: [
    RouterModule
  ],
  declarations: [
    LoginComponent
  ]
})
export class LoginRouterModule {}

login.module.ts

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

import {ComponentsModule, SharedModule} from '../../../shared';
import {LoginComponent} from './login.component';
import {LoginRouterModule} from './router';

@NgModule({
  imports: [
    ComponentsModule,
    SharedModule,
    LoginRouterModule
  ],
  exports: [
    ComponentsModule,
    SharedModule,
    LoginRouterModule
  ]
})

export class LoginModule {}

The issue arises when I add the children segment; suddenly, /admin stops functioning altogether and throws the error

Cannot match any routes. URL Segment: 'admin'
.

Is this not how child routes of a lazy loaded route are defined? How can I resolve this?

Answer №1

Upon reviewing the repository mentioned in my previous response to you:

In the example provided, the path is set as lazy/deep, corresponding to admin/login in your scenario.

To begin, I executed ng g module lazy/Deep --routing

Next, within

src/app/lazy/deep/deep-routing.module.ts
, the routes array was adjusted to:

<router-outlet> was added to the main component view of /lazy to enable rendering content from /lazy/deep inside it.

The key modification was made in the routing setup of lazy-routing.module.ts, facilitating lazy-loading of the lazy/deep route:

ng watch / npm start or ng build --watch, restarting is necessary for the changes to take effect.

For a detailed demonstration, refer to the deep-lazy-loading branch in https://github.com/Meligy/routing-angular-cli/tree/deep-lazy-loading

Answer №2

Ensure that you include a route with no path specified in your LoginModule.

login.module.ts

@NgModule({
  imports: [
    RouterModule.forChild({ path: '', component: LoginComponent }),
    ComponentsModule,
    SharedModule
  ],
  exports: [
    ComponentsModule,
    SharedModule
  ],
  declarations: [
    LoginComponent
  ]
})

export class LoginModule {}

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

problem with adjusting the form field depending on the circumstances

I am facing an issue with a form that displays a dropdown containing values such as users, receipts, companies, and reviewer. The visibility of these values should be based on the user's role. For example, if the role is admin, only users, receipts, a ...

Service injected with karma testing

I'm currently facing an issue while testing a component that has a service injected with a HTTP POST method. When I try to run the test using Karma, I encounter the following error message: TypeError: Cannot read property 'response' of unde ...

Issue encountered while implementing async functionality in AngularFireObject

I'm encountering difficulties with the async feature in AngularFireObject. Is there a solution available? Snippet from HomePage.ts: import { AngularFireObject } from 'angularfire2/database'; export class HomePage { profileData: Angu ...

How come TypeScript tuples support the array.push method?

In the TypeScript code snippet below, I have specified the role to be of Tuple type, meaning only 2 values of a specified type should be allowed in the role array. Despite this, I am still able to push a new item into the array. Why is the TS compiler not ...

Troubleshooting the Angular CLI issue: Module 'ansi-colors' not found

Having issues with my angular project, despite installing the latest version of NodeJs and NPM. When I try to run my project using the ng command, I encounter the following error message: Error: Cannot find module 'ansi-colors' Require stack: - ...

How to effectively handle null in Typescript when accessing types with index signatures unsafely

Why am I getting an error that test might be potentially undefined even though I've enabled strictNullCheck in my tsconfig.json file? (I'm unsure of the keys beforehand) const a: Record<string, {value: string}> = {} a["test"].va ...

Troubleshooting Error in Converting a JSX File with Tailwind CSS and Typescript

I found a code example on the Tailwind website. However, when I changed the file extension to .tsx, I encountered an error related to the className attribute. Do I need to specify a type for the className variable? What steps should I take to resolve thi ...

Is it possible to dynamically generate a form using ngFor in Angular 4?

I'm attempting to generate an editable form dynamically using ngFor. Essentially, it's a data grid and I might use some other systems for this task--perhaps that's the route I should take, but I wanted to give this approach a try initially. ...

Is it possible in Angular to directly bind the emitted output of a component to a property?

My primary application component communicates with its sub components using @Output decorated properties on the subcomponent. The output properties utilize an EventEmitter<>(). Typically, these properties emit a simple boolean or number. I want to di ...

Inconsistency with Angular 4 instance variables causes ambiguity within a function

Here is the code snippet: @Component({ selector: 'unb-navbar', templateUrl: './navbar.html' }) export class NavbarComponent implements OnInit { @Input() brand: string; controlador:boolean=false; overlay:string=""; @Input() menu ...

Can you determine the size of an unknown array in TypeScript?

Currently diving into TypeScript and tackling some TDD challenges. Within my model file, I'm working with a property named 'innovatorQuotes' that should be an array containing strings with a fixed length of 3. I'm struggling to nail dow ...

The efficiency of React Context API's setters is remarkably sluggish

I have a goal to implement a functionality where the background gradient of a page changes depending on whether the child's sublinks are expanded or collapsed. To achieve this, I am using the useContext hook. However, I've noticed that although e ...

The chosen sidebar item fails to show the respective component

Is there a way to show a component when the user clicks on the sideNav? Currently, I have managed to display the SideBarNavigation using ng-simple-sidebar. However, when I click on a sidebar item, the component opens as a new page instead of being display ...

Is it possible for two-way binding to function in index.html within Angular 4?

Does two-way binding function in index.html? I have some links and metadata in index.html. How can we define head parameters in a component? <head> <meta name="og:title" content={{titleValue}}> <meta name="og:url" content={{urlValue}}> & ...

Show the value in Angular in a dynamic way

My template needs to display the text 'Passed' only if item.name === 'michael' is not true. The component receives data in an array called courses[] from its parent. There are two interfaces, Courses and Teachers, where each course ID h ...

Extract and preserve elements from an ordered array by segregating them into separate arrays of objects using Angular 8

I have an array called arrayReceived containing 15 objects. My goal is to sort and store the first 6 objects with the lowest amount value in a new array called arraySorted. These objects are sorted based on their amount parameter. There may be multiple obj ...

The Node.js application is having trouble connecting to the Angular application on port 3000 when the Angular app is hosted on a remote machine

I'm facing an issue with my Nodejs app not being able to connect with the Angular app on port 3000 when the Angular app is hosted on a remote machine. However, everything works fine when both apps (Nodejs and Angular) are hosted on the same machine. C ...

What is the best way to expand all parent nodes of a specific child node in Angular 8 using the nested tree control of the mat tree?

getBookOutlineBar method is designed to take a list of nodes along with the selected node that needs to be highlighted when the outline sidebar opens. However, the current implementation only expands one specific node instead of all parent nodes. For exam ...

What is the best way to save data generated in Angular to a file using Node.js?

After researching, I have discovered the method for saving data in a file using node.js save(): void { this.modeler.saveXML((err: any, xml: any) => console.log('Result of saving XML: ', err, xml)); } } ...

Discovering the specific type of an object property in TypeScript

I am currently working on implementing a lookup type within an object. Imagine my object structure as follows: class PersonList { persons = { john: 'description of john', bob: 'description of bob' } } I want to create a ge ...