Angular 4中子组件间RouterLink配置问题求助
你的路由配置层级和结构有点小问题,而且懒加载模块的路由应该放在对应模块的路由文件里,不是直接塞在app-routing里。我给你整理了一套正确的配置方案,一步步来:
1. 确认主路由配置(app-routing.module.ts)
你的主路由懒加载配置是对的,保持不变就行,不过Angular 8+更推荐用箭头函数的懒加载写法(比字符串引用更规范):
const routes: Routes = [ // 其他主路由... { path: 'quiz', loadChildren: () => import('./quiz/quiz.module').then(m => m.QuizModule) } ];
2. 配置Quiz模块的内部路由(quiz-routing.module.ts)
在QuizModule对应的路由文件里,我们需要明确question和它的子路由answer的层级关系:
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ViewComponent } from './view/view.component'; // 你的question页面组件 import { AnswerComponent } from './answer/answer.component'; // 你的answer组件 const routes: Routes = [ { path: '', // 对应主路由的/quiz路径 children: [ { path: 'question', // 完整访问路径:/quiz/question component: ViewComponent, children: [ { path: 'answer', // 完整访问路径:/quiz/question/answer component: AnswerComponent } ] } ] } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class QuizRoutingModule { }
3. 在ViewComponent(question页面)中添加<router-outlet>
因为answer是question的子路由,所以必须在ViewComponent的模板里加一个<router-outlet>,这样AnswerComponent才能渲染在Question页面的指定位置:
<!-- view.component.html --> <!-- 方式一:用routerLink直接跳转(推荐) --> <h1 [routerLink]="['answer']">点击标题跳转至Answer</h1> <!-- 子路由组件会渲染在这个位置 --> <router-outlet></router-outlet>
4. 跳转方式(两种可选)
声明式跳转(routerLink)
直接在标题元素上绑定routerLink,因为是相对当前路由(/quiz/question),所以用相对路径['answer']就可以,这是最简洁的方式。
编程式跳转(Router服务)
如果需要在跳转前做一些逻辑处理,可以在组件类里注入Router服务:
// view.component.ts import { Router, ActivatedRoute } from '@angular/router'; constructor( private router: Router, private route: ActivatedRoute // 用于相对路径跳转 ) { } goToAnswer(): void { // 相对当前路由跳转 this.router.navigate(['answer'], { relativeTo: this.route }); // 也可以用绝对路径跳转,不用依赖ActivatedRoute // this.router.navigate(['/quiz/question/answer']); }
然后在模板里绑定点击事件:
<h1 (click)="goToAnswer()">点击标题跳转至Answer</h1>
关键注意点
- 懒加载模块的路由必须用
RouterModule.forChild()配置,不能用forRoot()(forRoot()只能在根模块用一次) - 子路由对应的父组件(这里是ViewComponent)必须包含
<router-outlet>,否则子组件无法渲染 - 确保组件的导入路径正确,避免出现“找不到组件”的编译错误
内容的提问来源于stack exchange,提问作者yer
相关产品推荐
相关产品推荐

