Angular中如何点击元素跳转至新组件且不显示原有组件内容?
实现步骤
1. 配置路由规则
首先打开项目根目录下的app-routing.module.ts文件,在routes数组中新增zoo组件的路由映射:
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; // 导入你生成的ZooComponent import { ZooComponent } from './zoo/zoo.component'; const routes: Routes = [ { path: 'zoo', component: ZooComponent }, // 可选配置:默认路由指向首页、404路由兜底 { path: '', redirectTo: '', pathMatch: 'full' }, { path: '**', redirectTo: '' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
注意:如果项目没有自动生成
app-routing.module.ts,需要在app.module.ts的imports数组中手动导入RouterModule.forRoot(routes),并声明上面的routes数组。
2. 调整根组件结构(保证跳转后仅显示zoo组件内容)
要实现跳转后完全隐藏根组件的原有内容、仅展示zoo组件,推荐将根组件中原有页面内容拆分到独立的首页组件中:
- 执行命令生成首页组件:
ng g c home - 把
app.component.html里原来的所有内容(包括你写的zoo section)剪切到home.component.html中 - 把
app.component.html的内容替换为唯一的路由出口标签:<router-outlet></router-outlet> - 回到
app-routing.module.ts,在routes数组中新增默认路由指向首页:
// 先导入HomeComponent import { HomeComponent } from './home/home.component'; const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'zoo', component: ZooComponent }, { path: '**', redirectTo: '' } ];
3. 给section元素添加点击跳转能力
两种实现方式可选:
方式1:使用routerLink指令(推荐)
直接在home.component.html的section标签上添加routerLink属性即可:
<section id="zoo" routerLink="/zoo" style="cursor: pointer;">Zoo</section>
加
cursor: pointer是为了让鼠标悬浮时显示点击手势,提升交互体验。
方式2:使用点击事件触发路由跳转
如果需要在跳转前做额外逻辑判断,可以用这种方式:
- 修改section标签绑定点击事件:
<section id="zoo" (click)="goToZoo()" style="cursor: pointer;">Zoo</section>
- 在
home.component.ts中注入Router并实现跳转方法:
import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent { constructor(private router: Router) { } goToZoo(): void { // 可在此处添加跳转前的校验逻辑 this.router.navigate(['/zoo']); } }
验证效果
启动项目后,默认展示首页的section元素,点击该元素后地址栏变为http://localhost:4200/zoo,页面仅展示zoo组件的内容。
内容的提问来源于stack exchange,提问作者JayNewbie
相关产品推荐
相关产品推荐

