Angular中的路由配置、路由重定向、默认选中路由

港控/mmm° 2023-10-06 09:04 153阅读 0赞

场景

Angular介绍、安装Angular Cli、创建Angular项目入门教程:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/105570017

Angular新建组件以及组件之间的调用:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/105694997

通过以上搭建起Angular项目。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

参照上面博客在新建Angular项目时选择添加路由

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0JBREFPX0xJVU1BTkdfUUlaSEk_size_16_color_FFFFFF_t_70

然后参照上面新建组件的方式新建三个组件

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0JBREFPX0xJVU1BTkdfUUlaSEk_size_16_color_FFFFFF_t_70 1

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

默认的代码结构为

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0JBREFPX0xJVU1BTkdfUUlaSEk_size_16_color_FFFFFF_t_70 2

首先需要引入组件

  1. import { ParentComponent } from './components/parent/parent.component';
  2. import { ChildComponent } from './components/child/child.component';
  3. import { NewsComponent } from './components/news/news.component';

这里引入的组件就是你需要配置的组件

然后配置路由

  1. const routes: Routes = [
  2. {path:'parent',component:ParentComponent},
  3. {path:'child',component:ChildComponent},
  4. {path:'news',component:NewsComponent}
  5. ];

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

  1. <header class="header">
  2. <a routerLink = "/parent">父组件</a>
  3. <a routerLink = "/child">子组件</a>
  4. <a routerLink = "/news">新闻</a>
  5. </header>
  6. <router-outlet></router-outlet>

使用routerLink进行路由的跳转,为了显示上更有效果,这里给header在app.component.scss中添加了样式

  1. .header{
  2. height: 44px;
  3. line-height: 44px;
  4. background: #000;
  5. color: #fff;
  6. a{
  7. color: #fff;
  8. padding: 10px 40px;
  9. }
  10. }

然后运行项目看效果

20200517225348626.gif

匹配不到路由时路由重定向

如果匹配不到路由或者路由所加载的组件时可以设置任意路由跳转路径,这里使其重定向到新闻组件

  1. {
  2. path:'**',
  3. redirectTo:'news'
  4. }

效果

2020051722535879.gif

设置默认选中路由

怎样设置路由选中时样式改变的效果

在html中添加routerLinkActive

  1. <a routerLink = "/parent" routerLinkActive="active">父组件</a>
  2. <a routerLink = "/child" routerLinkActive="active">子组件</a>
  3. <a routerLink = "/news" routerLinkActive="active">新闻</a>

然后在scss中添加active样式为字体为红色

  1. .active{
  2. color: red;
  3. }

效果

20200517225414482.gif

发表评论

表情:
评论列表 (有 0 条评论,153人围观)

还没有评论,来说两句吧...

相关阅读

    相关 配置默认

    配置接口IP地址并通过静态路由、默认路由配置实现全网互通 拓扑图如下;按照图上内容配置环境,pc机IP、子网掩码、网关 ![拓扑.PNG][.PNG] 路由器R1