我有使用以下结构的路线和子路线
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
我可以通过使用单击处理程序传递子组件来导航吗?
你可以这样做:
constructor(private route: ActivatedRoute, private router: Router) { }
toClicked(){
this.router.navigate(['./child-two'], {relativeTo: this.route});
}
有关更多详细信息,请查看relative routes chapter in the docs。