2016-11-20 35 views
2

我有路由和子路由採用以下結構角2路由器導航使用組件路徑,而不是完整的路徑

export const routes: Routes = [ 
    { path: '', redirectTo: 'component-one', pathMatch: 'full' }, 
    { path: 'component-one', component: ComponentOne }, 
    { path: 'component-two/:id', component: ComponentTwo, 
    children: [ 
     { path: '', redirectTo: 'child-one', pathMatch: 'full' }, 
     { path: 'child-one', component: ChildOne }, 
     { path: 'child-two', component: ChildTwo } 
    ] 
    } 
]; 

現在,如果我要定位到兒童航線childTwo所以裏面componentTwo我有以下。

<a [routerLink]="['child-two']"> 

這個工程。

但是如果我想要一個按鈕來做同樣的事情而不是鏈接會怎麼樣。

所以我試圖用一個按鈕的替代方法,如下

<button (click)="toClicked()">Two</button> 

然後,我有以下單擊處理

toClicked(){ 
    this.router.navigate(['component-two','child-two']); 
} 

正如你可以看到,如果我有聯繫我只需要提供兒童路線childTwo,但使用帶點擊處理程序的按鈕我將不得不提供父組件component-two以及兒童childTwo

我可以通過使用點擊處理程序傳遞子組件來導航嗎?

回答

2

你可以這樣說:

constructor(private route: ActivatedRoute, private router: Router) { } 

toClicked(){ 
    this.router.navigate(['./child-two'], {relativeTo: this.route}); 
} 

看看在relative routes chapter in the docs瞭解更多詳情。