资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Angular中路由及其用法的示例

这篇文章主要介绍了Angular中路由及其用法的示例,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

创新互联公司成立于2013年,我们提供高端网站建设公司成都网站制作成都网站设计、网站定制、营销型网站小程序设计、微信公众号开发、营销推广服务,提供专业营销思路、内容策划、视觉设计、程序开发来完成项目落地,为履带搅拌车企业提供源源不断的流量和订单咨询。

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

1、命令创建项目

ng new ng-demo --skip-install

Angular中路由及其用法的示例

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

感谢你能够认真阅读完这篇文章,希望小编分享的“Angular中路由及其用法的示例”这篇文章对大家有帮助,同时也希望大家多多支持创新互联,关注创新互联行业资讯频道,更多相关知识等着你来学习!


网页名称:Angular中路由及其用法的示例
URL地址:
http://cdkjz.cn/article/ihpjds.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220