how to navigate from sibling component to another sibling component in Angular?

别等时光非礼了梦想. 提交于 2021-01-28 00:24:31

问题


Below is my app.routing.ts

export const Approute: Routes = [
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: 'home',
    component: HomeComponent,
    children: [
      {
        path: 'dashboard',
        component: DashboardComponent
      },
      {
        path: 'trip-details',
        component: TripDetailsComponent
      }
    ]
  },
  { path: 'not-found', component : NotFoundComponent },
  { path: '**', redirectTo: '/not-found' }
 ];

component.ts

 viewDetails(details) {
     ...
    this.route.navigate(['../trip-details']);
  }

Above i have a component and am trying to navigate to another sibling component but am not able to navigate to http://localhost:4200/home/trip-details its redirecting me to http://localhost:4200/not-found.

Where am doing wrong?


回答1:


You can specify relativeTo which route as shown below:

import {Router, ActivatedRoute } from '@angular/router';
constructor(private r: ActivatedRoute) { }

viewDetails(details) {
    ...
    this.route.navigate(['../trip-details'], { relativeTo: this.r });
  }



回答2:


You should navigate like this:

this.route.navigate(['home', 'trip-details']);

Or, move trip-details one level higher in the routes, and then you can navigate to it directly with

this.route.navigate(['trip-details']);



回答3:


Because angular can not found the url as ../trip-details

You should use this.route.navigate(['/home/trip-details']);

Juse add 'home' in front of the url



来源:https://stackoverflow.com/questions/49487197/how-to-navigate-from-sibling-component-to-another-sibling-component-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!