The issue of Angular2 routing not working with an empty route has been

My routing setup is structured as follows:

In the app module, I have defined the initial level of routing using the following configuration:

const routes: Routes = [
{ path: 'login', component: LoginComponent, },

 { path: 'dash', redirectTo:"dashboard" },
 { path: '**', component: NotFoundComponent }

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

Within the app component, I have included

<router-outlet></router-outlet>
.

Furthermore, I created a dashboard module with its own routing configuration outlined below:

const dashboardRoutes: Routes = [
 {
   path: '',  //null path to utilize dashboardtemplate which includes sidebar links
   component: DashboardTemplateComponent,
   children: [
  {
    path: 'profile',
    component: ProfileComponent,

  },
  {
    path: 'dashboard',
    component: DashboardComponent, 

  },
  {
    path: 'users',
    component: UsersComponent,
  },


   ]
 }

 ];

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

Additionally, there is a dashboard template component defined as:

@Component({
  template: `
      <dash-side></dash-side>
      <router-outlet></router-outlet>`
})
export class DashboardTemplateComponent implements OnInit {

//logic for navigation based on user login status

  }

The objective was to allow the profile and users components to access the sidebar links within the DashboardTemplate component.

An issue arises when trying to navigate to the profile component within the dashboard route resulting in redirecting to the NotFoundComponent. How can this problem be resolved?

Answer №1

We have identified several key issues that need to be addressed.

  • Ensure that the redirect route has a slash prefix and includes pathMatch.

  • When importing RouterModule in the main routes file, use RouterModule.forChild(routes).

  • Import RouterModule as RouterModule.forRoot() into the imports section of the AppModule.

Implementing these changes should help resolve the problem you are experiencing.

const routes: Routes = [
    {
        path: 'login',
        component: LoginComponent
    },
    {
        path: 'dash',
        redirectTo:"/dashboard",  // <=== remember to add prefix slash
        pathMatch: 'full'         // <=== Don't forget to include 'pathMatch'
    },
    {
        path: '**',
        component: NotFoundComponent
    }
];
@NgModule({
    imports: [RouterModule.forChild(routes)],  // <=== make sure to switch to forChild()
    exports: [RouterModule],
    providers: []
})

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

Guide on integrating an element into a different element in a Vue 3 Tree Viewer

In my current setup, I've implemented a TreeView component that holds a tree. Each tree entry includes Children with their own unique label, perm, and further children. Take a look at an example of the tree: App.vue let tree = ref({ label: 'o ...

Utilize the import feature to bring in a paragraph from a separate file within your

Hey there! I've encountered a little issue. I'm trying to access an object from another component in the ability.component.html file but for some reason, the last paragraph (h1) is not functioning properly. Any idea why? app.component.ts @Compo ...

Populating an empty array with new objects

The problem I'm facing revolves around the Typescript aspect of an Angular application. I am dealing with a data array that I receive from a subscription. It consists of multiple objects with "titleName" and "ID" properties, but their number is neith ...

Implementing custom error handling in GraphQL using TypeORM and Apollo

Hey there, I'm currently working on implementing a custom error handling feature in my application. An example scenario is when a user tries to create an account with an email that already exists: { "errors": [ { "message": "The email exi ...

Error encountered following the upgrade of Angular and RxJS 5 to 6: Compilation failed

Since updating my libraries to the latest Angular 6 and RxJS 6, I've encountered an issue. I have a RouteService class that functions as a service. It utilizes the HttpClient to fetch data from a remote API. However, after the update, I'm facing ...

Excessive wait times during the construction of a moderately sized application (over 2 minutes) using TypeScript and loaders like Vue-Loader and TS-Loader

I'm currently utilizing Nuxt 2 with TypeScript and the most up-to-date dependency versions available. Even though my app is of medium size, the compilation time seems excessively slow. Here are my PC specs: Ryzen 7 2700X (8 Cores/16 Threads) 16 GB D ...

Find what you're looking for by exploring the search results inside the text box marked

update1: Appreciate your response! However, I am facing an issue where typing 'h' displays a set of values. When selecting a value, it should appear in the text box with a cross symbol, similar to how tags are edited on StackOverflow. I am work ...

Element remains intact after DOM manipulation even during router navigation

One of my directives has the functionality to relocate the element it is applied to on the body of the document: @Directive({ selector: '[myDirective]' }) export class MyDirective implements AfterViewInit { constructor(private elem: ElementR ...

Upon launching Google Chrome, a series of errors plague the WSL2 Ubuntu setup while running Karma and Jasmine for Angular testing

My Angular project utilizes Google Chrome for testing with Karma & Jasmine, but upon starting Chrome, I encounter multiple errors. Despite trying various solutions found on Stack Overflow, none have been successful. The versions in use are: Chrome 99.0.4 ...

Removing a request that lacks the id parameter in a .NET WebAPI

My .net core WebApi is functioning flawlessly, except when I use [HttpDelete] instead of [HttpDelete("{id}")]. Why might this be happening? Here is my URL: http://localhost:5004/api/Student/DeleteStudent/23 [ApiController] [Route("api/[controller]/[actio ...

Automatically adjusting column heights

I'm currently dynamically creating a group of columns, as demonstrated below: <div *ngFor="let col of colList"> <corp-column [xs]="'12'" [sm]="'6'"> <div class="tile tile-default"> <div cla ...

The nb-install mixin is not recognized

While working with angular5, I encountered the 'No mixin named nb-install' error when running npm start or serve Module build failed: undefined ^ No mixin named nb-install Backtrace: stdin:13 in E:\mrb_bugfixes& ...

Unexpected behavior with AWS DynamoDB ScanInput ExpressionAttributeValue

I crafted a scan query to only retrieve enabled data in the following way: const FilterExpression = 'enabled = :enabled'; const ExpressionAttributeValues = { ':enabled': { 'BOOL': true } }; const scanParameters: Sc ...

Set up a Git/TFS remote repository to synchronize with two separate local repositories

Our team has been working hard on developing a cutting-edge web app using Angular 6. To enhance the user interface, we've implemented Wijmo as one of our front-end frameworks throughout the application. However, we are currently using a -rc (release-c ...

Struggling with making the Angular directive compatible with ng-container

Below is the code snippet where the ng-if condition is not behaving as anticipated If the value of displayGroup is D, it should display the first and second blocks. Can you spot any error in my logic? <div *ngIf="(bookTravelInfo.displayGroup | upp ...

Is it possible to automatically set focus on the input box in an html tag multiple times instead of just once with autofocus?

Currently, I am developing an online editor that allows users to quickly edit individual words. My approach involves replacing specific words with input boxes containing the word for direct editing by users. In order to streamline the process and ensure e ...

Encountering a tuple type TypeScript error with a spread argument is far too frequent an occurrence

Encountering this error is becoming a frequent occurrence for me, and I am currently unable to resolve it. src/graphics.ts:105:55 - error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. 105 _queue.forEach((_ ...

Can you explain the variances between ngx-translate and ngx-i18next for me?

As ngx-i18next serves as a wrapper for i18next, I am curious about the specific differences in translation capabilities between ngx-translate and i18next. ...

Encountering a problem when making a HTTPS GET request to a REST API using

I am currently running an Angular application that utilizes an external API to fetch country ISOs. However, I am encountering an error with the API since it uses HTTPS. Interestingly, when I implement a proxy in my Angular local environment by mapping /is ...

"Attempting to verify a JSON Web Token using a promise that returns an object not compatible with the specified

Learning about Typescript has been quite a challenge for me, especially when it comes to using the correct syntax. I have implemented a promise to retrieve decoded content from jwt.verify - jsonwebtoken. It is functioning as intended and providing an obje ...