查看: 30|回覆: 0

Angular中路由的嵌套-父子路由

[複製鏈接]

4

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2009-9-4
發表於 2020-5-19 22:44:00 | 顯示全部樓層 |閲讀模式

场景

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;
    }
}

 

 

运行项目看效果 

回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部