Angular学习之---路由基础(一)

本文详细介绍如何在Angular项目中使用路由功能,包括配置路由模块、创建路由组件、使用RouterLink和RouterOutlet等关键元素,并演示了如何通过导航方法实现页面间的跳转。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.新建带路由配置的项目
ng new router –routing 会自动生成app-routing.module.ts文件
相关对象介绍:
这里写图片描述
简单解释:
Routes用法:path:‘user’,component:XXXComponent 指定显示的组件 注意(path不能用/XX,出现路径问题)
RouterOutlet:插座 使子组件在父模板中指定位置显示(html)
RouterLink:在父模板中通过a标签指向其他组件(html)
Router:组件中调用navigate()方法改变导航栏中的地址(component)
ActivatedRoute:保存传递路由时的参数信息和地址

需求:点击按钮1页面显示内容 ‘按钮1text’点击按钮2页面显示 ‘按钮2text’
1.新建组件showOne和showTwo
2.在html中设置不同的text以便区分
3.在app-routing.module文件中设置路径

const routes: Routes = [
//默认 path:'**'时为缺省路由
  {path:'',component:ShowOneComponent},
  {path:'test',component:ShowTwoComponent}
];

4.app.component.html文件

//默认路径 当前路径为根路径 若为./表示为子路径 (在child子路径中会用到)routerLink可以传递路径和参数
<a [routerLink]="['/']"></a>
<a [routerLink]="['/test']"></a>
<router-outlet></router-outlet>

这里写图片描述
这里写图片描述

5.通过Router的negative方法跳转同样可以实现此功能
在app.component.html文件添加个button

<button (click)="showText()">button</button>

6.app.component.ts

 constructor(private router:Router){}

  showText(){
    console.log("rrrrr");
    this.router.navigate(['/test']);
  }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值