Exploring the routing hierarchy in Angular: Setting up parent and child

I'm completely new to Angular and I am in need of assistance with routing. The structure of my folders is as follows:

https://i.sstatic.net/qNT0W.jpg

There are two distinct layouts in my application - one for the login page, and another for the main admin page complete with sidebar and toolbar.

Upon logging in, I expected to see the dashboard page within the main layout, but it only displays the layout without the dashboard content.

app-routing.module.ts

const accountModule = () => import('./features/account/account.module').then(x => x.AccountModule);
const mainModule = () => import('./features/main/main.module').then(x => x.MainModule);

const routes: Routes = [
  { path: '', loadChildren: mainModule, canActivate: [AuthGuard] },
  { path: 'account', loadChildren: accountModule },

  // redirect to home if no matching route
  { path: '**', redirectTo: '' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

account-routing.module.ts

const routes: Routes = [
  {
    path: '', component: LayoutComponent,
    children: [
        { path: 'login', component: LoginComponent },
    ]
  }
];

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

main-routing.module.ts

const routes: Routes = [
  {
    path: '', component: LayoutComponent,
    children: [
        { path: 'dashboard', component: DashboardComponent },
        { path: 'client', component: ClientComponent },
    ]
  }
];

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

Could someone guide me on adjusting the route so that when accessing http://localhost:4200, the dashboard page within the main layout is displayed instead of just the layout itself? Alternatively, how can I set up a redirection to http://localhost:4200/dashboard if displaying both together isn't feasible? Any help would be greatly appreciated.

Answer №1

To properly configure your main-routing.module.ts file, you can utilize the match path full with an empty string to redirect to your desired path.

const routes: Routes = [
  {
    path: '', component: LayoutComponent,
    children: [
        { path: 'dashboard', component: DashboardComponent },
        { path: 'client', component: ClientComponent },
    ]
  },
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' },

];

UPDATE: Updated order for better functionality

const routes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
  {
    path: '', component: LayoutComponent,
    children: [
        { path: 'dashboard', component: DashboardComponent },
        { path: 'client', component: ClientComponent },
    ]
  },
];

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

Transferring information between components within AngularJS

export class AppComponent { title = 'shopping-cart'; ngOnInit() { } images = [ { title: 'At the beach', url: 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?ixlib=rb-4.0.3&ixid=MnwxMjA ...

Using Angular Ionic for a click event that is triggered by a specific class

I am utilizing Highcharts and would like to click on the legend upon loading. With the use of Angular Ionic, how can I trigger a click on the .highcharts-legend-item class within the ngOnInit() {} method? I am aiming to click on this class as soon as the ...

Pass JSON data from Angular service to component

I have encountered a challenge while trying to pass JSON data from my API service to a component without directly subscribing in the component. The issue arises when attempting to access the data outside of the subscription block, as it returns something u ...

Is it possible to import both type and value on the same line when isolatedModules=true?

Did you know with Typescript, you can do type-only imports? import type { Foo } from "./types" If the file exports both types and values, you can use two separate import statements like this: import type { Foo } from "./types"; import ...

"Production environment encounters issues with react helper imports, whereas development environment has no trouble with

I have a JavaScript file named "globalHelper.js" which looks like this: exports.myMethod = (data) => { // method implementation here } exports.myOtherMethod = () => { ... } and so forth... When I want to use my Helper in other files, I import it ...

Adding a ng-select field when a button is clicked

In my template, I am using ng2-select to allow users to select items. There is a button called "Add" that, when clicked, should display another select field with a list of different item categories. However, the current version of my code does not achieve ...

Angular 8 throws a TS2339 error, yet the code is functioning perfectly and delivering the desired output

Upon compiling my code, I encountered the following error: ERROR in src/app/home/home.component.ts:13:37 - error TS2339: Property 'name' does not exist on type 'string | Type'. Property 'name' does not exist on type &ap ...

CSS: Placing items within an ng-for loop utilizing the "fixed" position property

<ul class="nav nav-pills nav-stacked" style="list-style: none"> <li *ngFor="#el of dragZoneElems; #idx = index"> <h4 style="position: fixed; top:'idx'*10" [dragResponder]="el">{{el.first}} {{el.last}}</h4& ...

Adjust the size of an Angular component or directive based on the variable being passed in

I'm looking to customize the size of my spinner when loading data. Is it possible to have predefined sizes for the spinner? For example: <spinner small> would create a 50px x 50px spinner <spinner large> would create a 300px x 300p ...

typescript encounters issues with union type while trying to access object properties

I'm puzzled by the errors I'm encountering in my IDE with the following code: I defined some interfaces/types interfaces/types: interface GradientColor { type: string; value: { angle: string | number; colours: string[]; }; } inte ...

Using Angular 7 shared service to allow sibling components to exchange data between each other

In my Angular 7 application, I have two sibling components - a configurator component and a custom stepper component. The configurator component is responsible for fetching data from the API and performing calculations on it. I would like to display the ca ...

Alter the entity type when passing it as a parameter

Trying to alter the Entity type, I am invoking a function that requires two parameters - one being the entity and the other a location. However, when trying to assign a Type for the first entity, it throws an error: Error: Argument of type 'Node<En ...

A TypeScript interface creating a type with optional keys of various types while enforcing strict null checks

I am attempting to devise an interface in typescript that resembles the following: type MoveSpeed = "min" | "road" | "full"; interface Interval { min?: number, max?: number } interface CreepPlan { [partName: string] : Interval; move?: MoveSpe ...

NodeJS function does not pause for the PostgreSQL database call despite using await keyword

I am attempting to recursively insert entries into the database where each entry depends on the previous one (the ID of the previous entry will be the child_id of the next entry). However, I am facing difficulties in getting async/await to work correctly. ...

Restricting HTTP requests to once every 200 milliseconds in Angular 4 with filtering in place

In my current project, I am working on a page that utilizes an ngFor to display an array of objects. One of the features I want to implement is the ability for users to filter these objects by entering specific keywords in an input field. Since the data f ...

Having difficulties generating ngc and tsc AOT ES5 compatible code

I've explored various options before seeking help here. I have an angular2 library that has been AOT compiled using ngc. Currently, I am not using webpack and solely relying on plain npm scripts. Below is the tsconfig file being utilized: { "comp ...

Dynamic forms in Angular do not currently have validation support for forms with multiple parts

I am currently working on creating a dynamic form with multi-part answers using Angular's Dynamic Form example (https://angular.io/guide/dynamic-form) and live example (https://angular.io/generated/live-examples/dynamic-form/eplnkr.html). I have set u ...

Modify the JSON format for the API POST request

I need assistance with making an API POST call in Angular 8. The JSON object structure that needs to be sent should follow this format: -{}JSON -{}data -[]exp +{} 0 +{} 1 However, the data I am sending is currently in this format: - ...

Is there a method to globally import "typings" in Visual Code without having to make changes to every JS file?

Is there a method to streamline the process of inputting reference paths for typings in Visual Studio Code without requiring manual typing? Perhaps by utilizing a configuration file that directs to all typings within the project, eliminating the need to ...

Typescript implementation for a website featuring a single overarching file alongside separate files for each individual webpage

Although I've never ventured into the realm of Typescript before, I am intrigued by its concept of "stricter JS". My knowledge on the subject is currently very limited as I am just starting to experiment with it. Essentially, I have developed my own ...