Angular2 navigate from a component to a sibling component without tearing down the first

本小妞迷上赌 提交于 2019-12-07 23:35:32

问题


I've just started learning Angular2 and I want to build a very common "list-detail" style page similar to this: http://xgrommx.github.io/rx-book/index.html . When you click an item in left-bar it initiates a navigation to the center detail view without tearing down the left-bar. What's the best way to achieve this effect?

My current design is like the following:

When I start the home component, the list component(child1) will load immediately and it will call an external API to fetch the names (only names) of a list of items. When clicking a item name on the left, it will create a new Detail-component. The detail component fetch item detail in its ngOnInit method. I've tried using auxiliary routes to nest the two child components on the same page but it does not seem to work. My home routes look like this:

export const HomeRoutes: RouterConfig = [
  {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    component: HomeComponent,
    children: [
      {
        path: '',
        component: ListComponent
      },
      {
        path: ':item',
        component: DetailComponent
        outlet: 'detail'
      }
    ]
  }
];

And in my home.component.ts I simply have this:

  <h2>Home</h2>

  <router-outlet></router-outlet>

  <router-outlet name="detail"></router-outlet>

And the way I navigate to the detail view is calling navigate() in the list-component like this:

onSelect(item : string) {
    this.router.navigate(['/detail', item]);
  }

But everytime I click the any of the items the detail view does not show up and it shows error like this:

Error: Uncaught (in promise): Error: Cannot match any routes: 'home/item'
.

Am I on the right track of using Auxiliary route and is there any better way to achieve this feature?


回答1:


The current router version has some issues in navigating to aux outlet using routerLink and navigate method. You should build the full URL and use navigateByUrl.

this.router.navigateByUrl('/home/(list//detail:detail)

Plunker with example. Click on detail button and then admin. Admin is routed in admin outlet. Open in full screen to see URL formation.

The URL has following semantics

  1. Child path is separated by /
  2. If a path has siblings then it should be surrounded with parenthesis
  3. Sibling are separated by //
  4. Outlet and path is separated by :

    Parent/child/(gchild1//outletname:gchild2)

Another so question



来源:https://stackoverflow.com/questions/38363669/angular2-navigate-from-a-component-to-a-sibling-component-without-tearing-down-t

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