在Angular中,子路由可以在子组件中进行应用。下面是一个示例:
首先,在父组件的路由配置中定义子路由:
const routes: Routes = [
{
path: 'parent',
component: ParentComponent,
children: [
{ path: 'child', component: ChildComponent }
]
}
];
然后,在父组件的模板中,使用
来显示子组件:
Parent Component
接下来,在子组件的模板中,可以添加其他内容和逻辑:
Child Component
最后,在父组件的模块中,导入RouterModule
和子组件,并将子路由配置添加到父路由配置中:
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { ParentComponent } from './parent.component';
import { ChildComponent } from './child.component';
const routes: Routes = [
{
path: 'parent',
component: ParentComponent,
children: [
{ path: 'child', component: ChildComponent }
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ParentRoutingModule { }
这样,当用户访问/parent
路径时,父组件将显示,并在父组件的模板中显示子组件。当用户访问/parent/child
路径时,子组件将显示在父组件的模板中的
位置。
这是一个简单的示例,你可以根据自己的需求进行更改和扩展。
上一篇:Angular子路由与样式的问题