Angular中的路由配置、路由重定向、默認選中路由


場景

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項目時選擇添加路由 

 

 

然后參照上面新建組件的方式新建三個組件

 

 

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

默認的代碼結構為

 

 

首先需要引入組件

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

 

這里引入的組件就是你需要配置的組件

然后配置路由

const routes: Routes = [
  {path:'parent',component:ParentComponent},
  {path:'child',component:ChildComponent},
  {path:'news',component:NewsComponent}

];

 

找到app.component.html跟組件模板,配置router-outlet顯示動態加載的路由

<header class="header">

    <a routerLink = "/parent">父組件</a>
    <a routerLink = "/child">子組件</a>
    <a routerLink = "/news">新聞</a>

</header>
<router-outlet></router-outlet>

 

使用routerLink進行路由的跳轉,為了顯示上更有效果,這里給header在app.component.scss中添加了樣式

.header{

    height: 44px;
    line-height: 44px;

    background: #000;

    color: #fff;

    a{

        color: #fff;

        padding: 10px 40px;
    }

}

 

 

然后運行項目看效果

 

 

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

如果匹配不到路由或者路由所加載的組件時可以設置任意路由跳轉路徑,這里使其重定向到新聞組件

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

效果

 

 

 

設置默認選中路由

怎樣設置路由選中時樣式改變的效果

在html中添加routerLinkActive

    <a routerLink = "/parent" routerLinkActive="active">父組件</a>
    <a routerLink = "/child" routerLinkActive="active">子組件</a>
    <a routerLink = "/news" routerLinkActive="active">新聞</a>

然后在scss中添加active樣式為字體為紅色

    .active{

        color: red;
    }

 

效果

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM