Unusual behavior and confusion encountered with loadChildren in Angular 7 routing

I've encountered a strange behavior while using loadChildren in my application and I'm quite confused about why it's happening.

Here is the content of my app-routing-module.ts:

const routes: Routes = [
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    component: InformationPageComponent,
    data: {
      title: 'INFO',
      preTitle: 'VISUALIZZA_MODELLO'
    },
  },
  {
    path: '',
    loadChildren: './visualizza-modello/modello.module#ModelloModule',
    canActivateChild: []
  }, 
  {
    path: '**',
    component: PageNotFoundComponent//HomeComponent
  }
];

Furthermore, in my modello-routing-module.ts, this is what I have:

@NgModule({
  imports: [
    RouterModule.forChild([
      {
        path: 'visualizza-modello',
        data: {
          title: 'DELEGHE',
          breadcrumb: 'VISUALIZZA_MODELLO',
          preTitle: 'VISUALIZZA_MODELLO',
        },
        children: [
          {
            path: 'dettaglio-ditta',
            data: {
              title: 'RICERCA_PAT',
              breadcrumb: 'RICERCA_PAT',
              preTitle: 'VISUALIZZA_MODELLO'
            },
            children: [
              {
                path: 'dettaglio-quadro',
                data: {
                  title: 'DETTAGLIO_MODELLO',
                  breadcrumb: 'VISUALIZZA_MODELLO',
                  preTitle: 'VISUALIZZA_MODELLO'
                },
                component: DettaglioQuadroComponent
              },
              {
                path: '',
                data: {
                  title: 'RICERCA_PAT',
                  breadcrumb: '',
                  preTitle: 'VISUALIZZA_MODELLO'
                },
                component: DettaglioDittaComponent,
              }
            ]
          },
          {
            path: '',
            data: {
              title: 'DELEGHE',
              breadcrumb: '',
              preTitle: 'VISUALIZZA_MODELLO'
            },
            component: DelegheComponent
          },
        ]
      },
    ])
  ],
  exports: [RouterModule]
})

My desired behavior is as follows:

Upon opening the project, I'd like to be routed to the home page. When clicking on the "Visualizza Modello" menu item, I expect to be taken to that specific page. And if I click on "Home" within the breadcrumb navigation, I should return to the home page.

While this setup generally works, there are occasions when leaving and returning to the page results in only a blank page being displayed instead of the home page.

If you have any ideas on how to resolve this issue, please share them with me!

Answer №1

It seems that the comments are accurate - having two empty paths won't work.

If your application routing is properly set up, it should resemble something like this:

app-routing-module.ts

const routes: Routes = {
    {
        path: '', redirectTo: 'home', pathMatch: 'full'
    },
    {
        path: 'home', component: HomeComponent
    },
    {
        path: 'view-model', loadChildren: './view-model/model.module#ModelModule'
    },    
    {
        path: '**', component: PageNotFoundComponent
    },
};

These are the top-level routes for your application. Any additional pages you want to display within the main app component's <router-outlet> will need to be added to this list, similar to the view-model route.

Within your ModelModule, you will have the routes specific to that branch of routing. The implementation will vary depending on whether your 'new' top-level component includes a router-outlet.

If it is simply a set of pages to be displayed within the main app router-outlet, then you are essentially defining a new branch of paths that will be rendered in that top-level router:

model-view-routing.module.ts

const routes: Routes = {
    {
        path: '', component: ViewComponent // represents url.com/view-model at this point
    },
    {
        path: 'company-details', component: CompanyDetailsComponent // url.com/view-model/company-details
    },    
    {
        path: 'frame-details', component: FrameDetailsComponent // url.com/view-model/frame-details
    },    
    {
        ...
    }
};

Alternatively, if your main ViewComponent serves as a shell with its own router-outlet, then you are dealing with child paths.

The approach is quite similar; you just need to place those same paths inside the children property. The URLs remain the same, but the children will be rendered within the new router-outlet instead of the main one in the app.

model-view-routing.module.ts

const routes: Routes = {
    {
        path: '',
        component: ViewComponent,
        children: [
            {
                path: '', component: WhateverHomeComponent
            }
            {
                path: 'company-details', component: CompanyDetailsComponent // url.com/view-model/company-details
            },    
            {
                path: 'frame-details', component: FrameDetailsComponent // url.com/view-model/frame-details
            },    
            {
                ...
            }
        ]
    }
};

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

Zod: Establishing minimum and maximum values after converting a string to a numerical value

When dealing with a number or numeric string, I aim to convert it to a number and then validate it using the .min() and .max() methods. However, the results are not matching my expectations. const numberValid = z.number().or(z.string().regex(/^\d+$/). ...

Preserving quotation marks when utilizing JSON parsing

Whenever I try to search for an answer to this question, I am unable to find any relevant results. So please excuse me if this has been asked before in a different way. I want to preserve all quotation marks in my JSON when converting from a string. In m ...

What is the process for assigning a predefined type that has already been declared in the @types/node package?

Is there a way to replace the any type with NetworkInterfaceInfo[] type in this code snippet? Unfortunately, I am unable to import @types/node because of an issue mentioned here: How to fix "@types/node/index.d.ts is not a module"? Here is the o ...

Implementing edit hyperlink functionality in Angular 4 using Jquery Datatable

Our Angular project is currently utilizing Jquery Datatable, and the grid is displaying successfully. Now, I am seeking assistance in adding an edit hyperlink at the end of each row. Could someone please guide me on how to achieve this? Below is a snippet ...

Information about the HTML detail element in Angular 2 is provided

Hi, I'm curious if there's a way to know if the details section is open or closed. When using <details (click)="changeWrap($event)">, I can't find any information in $event about the status of the details being open. I am currently wor ...

In what scenario would one require an 'is' predicate instead of utilizing the 'in' operator?

The TypeScript documentation highlights the use of TypeGuards for distinguishing between different types. Examples in the documentation showcase the is predicate and the in operator for this purpose. is predicate: function isFish(pet: Fish | Bird): pet ...

Ways to apply the strategy pattern in Vue component implementation

Here's the scenario: I possess a Cat, Dog, and Horse, all of which abide by the Animal interface. Compact components exist for each one - DogComponent, CatComponent, and HorseComponent. Query: How can I develop an AnimalComponent that is capable of ...

Deploying a Typescript-enabled Express application on the Azure cloud platform

Currently, I am attempting to deploy an Express server on Typescript on Azure by following the guidelines provided in this tutorial: https://learn.microsoft.com/en-us/azure/app-service/quickstart-nodejs?tabs=windows&pivots=development-environment-vsco ...

Angular formArray option buttons

I am currently working on incorporating a radio button group into a FormArray, but I'm encountering an issue where selecting a value changes the value for every member of the FormArray. It seems to be related to the formControlName, however, I am unsu ...

The iframe is not large enough to contain all the HTML content

I'm encountering a problem with a website I'm currently developing - specifically, I am struggling to embed an HTML document into an iframe in a manner that fills the entire page. Additionally, I am utilizing Angular to retrieve the HTML document ...

Issue encountered while executing ./node_modules/.bin/cucumber-js within GitLab CI

I've encountered an issue while setting up a continuous integration build for my node project. Despite the fact that npm run test runs smoothly in my local setup, I am facing an exception in GitLab CI. The error arises from the following test command ...

Obtaining a service instance without using constructor injection

I am facing an issue with retrieving an instance of a @Injectable service that is defined in Bootstrap. I am looking for a way to obtain the service instance without using constructor injection. I attempted to use ReflectiveInjector.resolveAndCreate but it ...

The error message "Property Routing does not exist on type 'typeof import'" indicates that the property "Routing

I have created a post but unfortunately, I haven't received any responses. Being new to leaflet, I am quite confused about what might be causing the issue. I followed all the instructions from the documents but I am still encountering errors. <lin ...

The declaration file for the 'react-tree-graph' module could not be located

I have been working on incorporating a tree visualization into my react project. After adding the 'react-tree-graph' package and importing the Tree module, like so: import Tree from 'react-tree-graph' I encountered the following error ...

Encountering an issue with React Hooks Form and MUI DatePicker when trying to select a different date causing an

I have been attempting to wrap the MUI date picker into a custom component. This is what I have done: export interface IMessage { id?: string | undefined; title?: string | undefined; content?: string | undefined; date?: Date | undefined; } ...

Error message thrown while using Angular2 Routing

I've been working on setting up a module to route the application, and although I believe I've set all the variables correctly, I seem to be missing something as I keep encountering this error: "Error: Uncaught (in promise): Error: Cannot find pr ...

Error: Unable to assign value to property 12 because the object does not support extensibility

I'm facing an issue with my client application as I cannot figure out the error I am encountering. Despite successfully subscribing to a GraphQL subscription and receiving updates, I am struggling to update the TypeScript array named "models:ModelClas ...

Tips for passing multiple parameters to Web API controller methods in Angular 4

Want to learn how to use Spring Rest Api: @RequestMapping(value={"/save-userlist"}, method=RequestMethod.POST) public ResponseEntity<?> saveUserList(@RequestBody UserListDTO userListDTO, @RequestBody List<User> users, @RequestParam Integer ...

Using TypeScript to include a custom request header in an Express application

I am attempting to include a unique header in my request, but I need to make adjustments within the interface for this task. The original Request interface makes reference to IncomingHttpHeaders. Therefore, my objective is to expand this interface by intr ...

ngOnInit unable to properly listen to event stream

I've been trying to solve a persistent issue without success. The problem involves the interaction between three key elements: the HeaderComponent, TabChangingService, and TabsComponent. Within the HeaderComponent, there are three buttons, each with a ...