php angular使用,详解Angular中的路由及其用法

本篇文章带大家了解一下Angular中的路由,以及Angular路由的使用。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

0429440f672df8af7e5751164ee0c403.png

一、 Angular 创建一个默认带路由的项目

1、命令创建项目

ng new ng-demo --skip-install

530b3eac842c893bc210b3605a9c5508.png

2、创建需要的组件ng g component components/home

ng g component components/news

ng g component components/newscontent

3、找到 app-routing.module.ts 配置路由

引入组件import { HomeComponent } from './components/home/home.component';

import { NewsComponent } from './components/news/news.component';

import { ProductComponent } from './components/product/product.component';

配置路由const routes: Routes = [

{path: 'home', component: HomeComponent},

{path: 'news', component: NewsComponent},

{path:'product', component:ProductComponent },

{path: '*', redirectTo: '/home', pathMatch: 'full' }

];

4、找到 app.component.html 根组件模板,配置 router-outlet 显示动态加载的路由

首页

新闻

二、Angular routerLink 跳转页面默认路由首页

新闻//匹配不到路由的时候加载的组件 或者跳转的路由

{

path: '**', /*任意的路由*/

// component:HomeComponent

redirectTo:'home'

}

三、Angular routerLinkActive 设置 routerLink 默认选中路由

首页

新闻

首页

新闻

四、动态路由

4.1.问号传参

跳转方式,页面跳转或js跳转

问号传参的url地址显示为 …/list-item?id=1

queryParams属性是固定的

{{ item.name }}

//js跳转

//router为ActivatedRoute的实例import { Router } from '@angular/router';

.

constructor(private router: Router) {}

.

this.router.navigate(['/newscontent'],{

queryParams:{

name:'laney',

id:id

},

skipLocationChange: true

//可以不写,默认为false,设为true时路由跳转浏览器中的url会保持不变,传入的参数依然有效

});

获取参数方式import { ActivatedRoute } from '@angular/router';

constructor(public route:ActivatedRoute) { }

ngOnInit() {

this.route.queryParams.subscribe((data)=>{

console.log(data);

})

}

4.2 路径传参

路径传参的url地址显示为 …/list-item/1 {{ item.name }}

//js跳转 //router为ActivatedRoute的实例

this.router.navigate([’/list-item’, item.id]);

路径配置:{path: ‘list-item/:id’, component: ListItemComponent}

获取参数方式this.route.params.subscribe(

param => {

this.id= param['id'];

}

)

五、父子路由

1、创建组件引入组件import { WelcomeComponent } from ‘./components/home/welcome/welcome.component’;

import { SettingComponent } from ‘./components/home/setting/setting.component’;

2、配置路由{

path:'home',

component:HomeComponent,

children:[{

path:'welcome',

component:WelcomeComponent

},{

path:'setting',

component:SettingComponent

},

{path: '**', redirectTo: 'welcome'}

]

},

3、父组件中定义router-outlet

更多编程相关知识,请访问:编程视频!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值