在Angular中,子路由需要放在父路由的组件中,并且父路由的路径应该以斜杠(/)开头。以下是一个包含代码示例的解决方法:
首先,在父组件的HTML模板中,添加一个
标签,用于渲染子路由的组件。例如,假设父组件的路径为/parent
:
这是父组件
然后,在父组件的路由配置中,定义子路由。可以在children
属性中配置子路由的路径和对应的组件。例如,假设有两个子路由分别位于/parent/child1
和/parent/child2
:
// parent-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ParentComponent } from './parent.component';
import { Child1Component } from './child1.component';
import { Child2Component } from './child2.component';
const routes: Routes = [
{
path: 'parent',
component: ParentComponent,
children: [
{ path: 'child1', component: Child1Component },
{ path: 'child2', component: Child2Component }
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ParentRoutingModule { }
最后,在父组件的模块中导入并添加ParentRoutingModule
到imports
数组中:
// parent.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ParentComponent } from './parent.component';
import { Child1Component } from './child1.component';
import { Child2Component } from './child2.component';
import { ParentRoutingModule } from './parent-routing.module';
@NgModule({
declarations: [
ParentComponent,
Child1Component,
Child2Component
],
imports: [
CommonModule,
ParentRoutingModule
]
})
export class ParentModule { }
现在,当访问/parent
路径时,父组件将会被渲染,并且子组件的内容将会在
标签中进行渲染。例如,当访问/parent/child1
时,Child1Component
将会被渲染在父组件中。
希望以上解决方法能对你有所帮助!