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

运行项目看效果 

猜你喜欢

转载自www.cnblogs.com/badaoliumangqizhi/p/12920158.html