要导航到非子组件,我们需要使用路由对象和路由路径来手动导航。以下是一个具体的示例:
const appRoutes: Routes = [
{ path: 'home', component: HomeComponent},
{ path: 'about', component: AboutComponent},
{ path: 'parent', component: ParentComponent,
children: [
{ path: 'childOne', component: ChildOneComponent },
{ path: 'childTwo', component: ChildTwoComponent },
]
},
{ path: 'non-child', component: NonChildComponent } //添加非子组件的路由路径
];
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-parent',
template: `
Parent Component
`,
})
export class ParentComponent {
constructor(private router: Router) {}
navigateToChildOne() {
this.router.navigate(['/parent/childOne']); //导航到子组件
}
navigateToChildTwo() {
this.router.navigate(['/parent/childTwo']); //导航到子组件
}
navigateToNonChild() {
this.router.navigate(['/non-child']); //导航到非子组件
}
}
下一篇:Angular无法导航到其他组件