2017-03-16 126 views
11

有沒有方法在父路由的<router-outlet>中顯示子路由?Angular 2:讓子路由組件替換路由器插座中的父

例如,假設我們有兩個途徑:

/users/12345 

/users/12345/orders/12345 

我還需要第二次是第一個孩子,但我也需要與/users/12345/orders/12345反對的內容完全取代/users/12345內容/users/12345 sub router-outlet中有/users/12345/orders/12345

我以爲我可以通過命名父級路由器插座來實現這一點,並且讓兩條路由都以此爲目標,但是從我一直在做的研究(以及它造成的錯誤)中,我得到了這些名字的意圖因爲當已經存在一個主路由器出口二次使用

回答

7

您可以通過設置你這樣的途徑做到這一點:

const routes : Routes = [ 
    { 
    path : 'user/:id', 
    component : ParentComponent, 
    children : [ 
     { path : '', component : UserComponent }, 
     { path : 'odrer/:id', component : OrderComponent } 
    ] 
    } 
] 

ParentComponent的模板將只有<router-outlet>加載它的孩子。

0

由於不像這是目前可能的,直到它,我剛剛更新了我的佈局組件的類添加到自己如果它注意到有自身內的另一個佈局的構成要素:

@HostBinding('class.hasChildLayouts') hasChildLayouts: boolean; 

constructor(private router: Router, private el: ElementRef) { } 

ngOnInit() { 
    this.router.events 
     .filter(event => event instanceof NavigationEnd) 
     .subscribe(event => { 
      this.hasChildLayouts= (this.el.nativeElement as HTMLElement).querySelector('layout') != null; 
     }); 
} 

然後更新我的CSS隱藏/調整父元素,使其看起來正確。絕對不是理想的,但它是我能想到的唯一解決方案,保持了路線的父母/子女關係。

+0

那我的答案嗎?這不是你想要的嗎? – YounesM

+0

使用你的例子,問題是關於如何在router-outlet中使用'order /:id'替換'OrderComponent'中的'ParentComponent',該設置不會完成 – John

11

我有同樣的問題。這是我如何固定它:

const routes: Routes = [ 
    { 
    path: '', 
    children: [ 
     { 
      path: '', 
      component: ParentComponent, 
     }, 
     { 
      path: 'child', 
      component: ChildComponent, 
     } 
    ] 
    } 
]; 
2
let routes = [ 
    { 
    path: 'users/:id', 
    component: UsersComponent 
    }, 
    { 
    path: 'users/:id/orders/:id', 
    component: OrdersComponent 
    } 
]; 
相關問題