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項目。

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

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

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。

實現

如果要實現如下這種父子路由的嵌套

首先新建三個組件home組件、welcome組件、setting組件,其中home組件是父組件,welcome組件和setting組件是子組件

ng g component components/home
ng g component components/home/welcome
ng g component components/home/setting

 

 

然后在app-routing.module.ts中引入這三個組件並配置父子路由

import { HomeComponent } from './components/home/home.component';
import { WelcomeComponent } from './components/home/welcome/welcome.component';
import { SettingComponent } from './components/home/setting/setting.component';

 

const routes: Routes = [
   {
    
    path:'home',component:HomeComponent,

    children:[

      {path:'welcome',component:WelcomeComponent},

      {path:'setting',component:SettingComponent},

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

    }
];

 

最后一個兩個星號的路由配置是配置默認路由是歡迎組件的頁面。

然后在home頁添加路由跳轉

<div class="content">

    <div class="left">
  
        <a [routerLink]="[ '/home/welcome']" routerLinkActive="active">歡迎首頁</a>
  
        <br>
  
        <br>
        <a [routerLink]="[ '/home/setting']" routerLinkActive="active">系統設置</a>
  
    </div>
  
    <div class="right">
  
      <router-outlet></router-outlet>
  
    </div>
  
  </div>

為了讓子組件顯示在父組件中所以添加<router-outlet></router-outlet>

為了顯示出左右布局,所以在home的scss中添加樣式

.content{

    width:100%;
    height:500px;
    display:flex;

    .left{

        width:200px;
        border-right:1px solid #eee;
        height:500px;
    }
    .right{

        flex:1px;
    }
}

 

 

運行項目看效果 


免責聲明!

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



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