Loading lazy modules into tabs in Angular 8 - A comprehensive guide

I'm attempting to implement tabs with lazy loading of feature modules. Here is the code I have so far:

Main router:

export const AppRoutes: Routes = [{
    path: '',
    redirectTo: 'home',
    pathMatch: 'full',
  },
  { path: 'login', component: LoginComponent },
  {
    path: '',
    component: DefaultLayoutComponent,
    children: [
    {
      path: 'home', canActivate: [AuthGuard],
      loadChildren: './views/home/home.module#HomeModule'
    },
    {
      path: 'settings',
      loadChildren: './views/settings/settings.module#SettingsModule'
    },
  ]}
];

settings.module:

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { SettingsComponent } from './settings.component';
import { SettingsRoutingModule } from './settings-routing.module';

@NgModule({
  imports: [
    SettingsRoutingModule
  ],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
  declarations: [ SettingsComponent ]
})

export class SettingsModule { }

settings-routing.module:

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

import { SettingsComponent } from './settings.component';

const routes: Routes = [
  {
    path: '',
    component: SettingsComponent,
    data: {
      title: 'Settings'
    },
    children: [
      { path: 'syspref', loadChildren: './systempreferences/systempreferences.module#SystempreferencesModule' },
      { path: 'userpref', loadChildren: './userpreferences/userpreferences.module#UserpreferencesModule' },
    ]
  }
];

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

settings.component.html

<section id="tabs">
    <div class="container">
        <div class="row">
            <div class="col-xs-12" style="width: 100vw;">
                <nav>
                    <div class="nav nav-tabs nav-fill" id="nav-tab" role="tablist">
            <a class="nav-item nav-link" id="nav-syspref-tab" data-toggle="tab" href="#" role="tab" aria-controls="nav-syspref"
              aria-selected="false" routerLink="syspref">Default Preferences</a>
            <a class="nav-item nav-link" id="nav-userpref-tab" data-toggle="tab" href="#" role="tab" aria-controls="nav-userpref"
              aria-selected="false" routerLink="userpref">User Preferences</a>
                    </div>
        </nav>
                <div class="tab-content py-3 px-3 px-sm-0" id="nav-tabContent">
                    <div class="tab-pane fade show active" id="nav-syspref" role="tabpanel" aria-labelledby="nav-syspref-tab">
                    </div>
                    <div class="tab-pane fade" id="nav-userpref" role="tabpanel" aria-labelledby="nav-userpref-tab">
                    </div>
                </div>

            </div>
        </div>
    </div>
</section>
<router-outlet></router-outlet>

systempreferences.module

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SystempreferencesComponent } from './systempreferences.component';

@NgModule({
  imports: [
    CommonModule
  ],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
  declarations: [SystempreferencesComponent]
})
export class SystempreferencesModule { }

My goal was for selecting a tab to load a module like SystempreferencesModule and display the SystempreferencesComponent component, but that isn't happening. Am I misunderstanding something?

Appreciate any insights or guidance.

Answer №1

The method you are currently using to set up lazy loaded routes seems outdated. It was modified in Angular 7 or 8 (I believe...). The new approach should look like this:

{
    path: 'syspref',
    loadChildren: () => import('./systempreferences/systempreferences.module').then(m =>
    m.SystempreferencesModule)
},

Additionally, in your SystemPreferences module, make sure you include a route similar to the following:

const routes: Routes = [
  {
    path: '',
    component: SystempreferencesComponent,
  }
];

You can simply add the 'routes' variable at the beginning of your System Preferences module and insert the code below into your imports array (which is slightly easier than setting up a routing module but serves the same function):

RouterModule.forChild(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

How can I rename an event function in Angular 2?

Is it possible to dynamically change the function associated with an event? I attempted to do so like this: (click) = "{{myFunction}}" However, I encountered an error stating "Parser Error: Got interpolation ({{}}) where expression was expected". I am lo ...

Changing the host domain to a non-.com extension in Angular-cli while serving for development

While running an ng serve on my angular cli build, I am attempting to use a .ca domain as the host in order to address CORS and cookie issues during development. Interestingly, when using a .com domain, everything functions smoothly: Functioning with .com ...

The input of type 'Observable<true | Promise<boolean>>' cannot be assigned to the output of type 'boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree>'

I'm currently using a Guard with a canActivate method: canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { return this.fi ...

Troubleshooting issue with beforeEach in karma and Mocha after upgrading to Angular 4

Unique Context After verifying the successful "green" builds on the master branch, which utilizes angular-cli 1.0.0 and the older angular2 dependencies, my goal is to transition from angular2 to angular4. Issue Post Upgrade The application functions pr ...

Encountering a sort error in Angular 8 when attempting to sort an Observable

I am struggling to organize an observable that is retrieved from a service using http.get. I have attempted to sort the data both from the service and in the component after subscribing. However, I keep encountering the error "Sort is not a function". As ...

"Encountering an issue with mounting components in React Unit Testing with Jest and Typescript

Having developed a simple app with components, here is the code: import GraphicCanvas from './Graphing/GraphCanvas'; import { drawCircle } from './Graphing/DrawCircle'; function App() { return ( <div className="App"&g ...

React Typescript: exploring the power of dynamic types

Can dynamic typing be implemented? The JSON structure I am working with looks like this: { "fieldName": "Some text", "type": String, "inputType": "text" }, { "fieldName": "Some bool&q ...

The process of compiling and monitoring *two* Typescript packages, where one is reliant on the other

I'm in the process of creating a Typescript library located under src/ and sample files under examples/. The current directory structure is as follows: examples/ package.json exampleFiles.ts src/ index.ts package.json I am able to compil ...

Using Angular to send requests to a .net Web API

My attempt to send a POST request from my angular application to a .net Web API instance is resulting in the server returning null. server [HttpPost] public string callBcknd([FromBody]string body) { try { Log.Info(string.Format("{0}", bo ...

Difficulty with navigation buttons on multiple Bootstrap carousels implemented using ngFor in a single page

Currently, I'm engaged in developing a practice eCommerce platform where multiple product cards are showcased using data from a sample JSON file. Additionally, several Bootstrap carousels are integrated into the website to display images of each item. ...

Instructions on transferring JSON data to clipboard using a button

How can I copy JSON data to clipboard using a button click? { "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": [ ... ], "Resource": "*" } ] } I attempted to ...

Display a loader while waiting for an API call to complete within 5 seconds using Angular and RxJS operators. If the API call takes longer

We are actively working to prevent user blockage during file uploads by implementing a method in Angular using RxJS. How can I display a toastr message and hide the loader if the API does not complete within 5 seconds? uploadFile() { this.service.uploa ...

Encountering a Typescript error when trying to pass a function as a prop that returns SX style

Imagine a scenario where a parent component needs to pass down a function to modify the styles of a reusable child component: const getStyleProps: StyleProps<Theme> = (theme: Theme) => ({ mt: 1, '.Custom-CSS-to-update': { padding ...

Display nested components without the need for a parent container element - Divide SVG elements into individual components

I am currently working on splitting an SVG element within a component into separate parts and creating nested components dynamically from the parent component. This is necessary as I am constructing the entire SVG graphic based on a json file that dictates ...

Angular Service: AppleID is not recognized following the loading of the Apple script

I'm new to this forum and have been struggling to find a solution for my problem. I am attempting to integrate AppleConnect into my Angular 8 app with the following approach: I have created an appleService.ts file that dynamically generates the Apple ...

Utilizing Angular Services to Share Events and Reusing Components Multiple Times on a Page

My unique custom table is made up of multiple components, each emitting events using a shared service called TableEvent. These events are subscribed to by a class named TableTemplate, which facilitates communication among the different components of the ta ...

Angular fails to display newly created objects unless the page is manually refreshed

Hey there, I'm facing a problem with my message service on the user profile page. Even though messages are fetched from the database and displayed correctly, any changes (such as creating or deleting a message) are not reflected until I manually refre ...

What are the benefits of precompiling my Typescript project for production instead of just running it directly with ts-node?

Many people recommend precompiling production builds. However, the reasoning behind this advice is not clear to me. What potential issues may arise from running a project in production using node --loader ts-node/esm src/server.ts ? ...

Hiding the keypad on an Android device in an Ionic app when user input is detected

I am currently utilizing the syncfusion ej2 Calendar plugin for a datepicker, but I am only using options such as selecting ranges like today, 1 month, or last 7 days from the plugin itself. The plugin provides dropdown options when the calendar is trigger ...

The map function is calling an unresolved function or method named "map"

I'm encountering an error with the map method in my code, even after correctly importing 'rxjs/add/operator/map'. I've followed all the necessary steps and upgraded to rxjs 5.0.1, but the error persists. Do you have any suggestions on h ...