1. 程式人生 > >Angular學習之旅-----父子路由

Angular學習之旅-----父子路由

home下welcome

shop下shoplist shopcate

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
// 引入元件
import { HomeComponent } from './components/home/home.component'
import { NewsComponent } from './components/news/news.component'
import { NewscontentComponent } from './components/newscontent/newscontent.component'
import { UserComponent } from './components/user/user.component'
import { ShoplistComponent } from './components/shoplist/shoplist.component'
import {ShopComponent} from './components/shop/shop.component'
import {WelcomeComponent} from './components/welcome/welcome.component'
import {ShopcateComponent} from './components/shopcate/shopcate.component'
const routes: Routes = [
  { path: 'home', component: HomeComponent,children:[{path:'welcome',component:WelcomeComponent},{ path: '**', redirectTo: 'welcome' }] }, // 配置子路由
  { path: 'news', component: NewsComponent },
  { path: 'shop', component: ShopComponent,children:[{path: 'shoplist', component: ShoplistComponent},{path: 'shopcate', component: ShopcateComponent},{ path: '**', redirectTo: 'shoplist' }] },
  { path: 'newscontent/:aid',   /*配置動態路由*/ component: NewscontentComponent },
  { path: 'user', component: UserComponent },
  // 設定預設路由
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  // 匹配不到任意路由的時候,載入home
  { path: '**', redirectTo: 'home' }

];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
<div class="con">
  <div class="left">
    <a routerLink="/shop/shoplist" routerLinkActive="active">商品列表</a>
    <a routerLink="/shop/shopcate" routerLinkActive="active">商品分類</a>
  </div>
  <div class="right">
    <!-- 動態載入的元件放在這個裡面 -->
    <router-outlet></router-outlet>
  </div>
</div>
<div>
  Home元件
  <button (click)="goNews()">js跳轉新聞</button>
  <a routerLink="/shoplist" routerLinkActive="active">去商品類別頁面</a>
  <hr>
  <button (click)="goShop(11,3)">get傳值1</button>
  <button (click)="goShop(12,3)">get傳值2</button>
  <button (click)="goShop(13,3)">get傳值3</button>
  <hr>
  <div class="con">
    <div class="left">
        <a routerLink="/home/welcome" routerLinkActive="active">歡迎介面</a>
    </div>
    <div class="right">
      <!-- 動態載入的元件放在這個裡面 -->
      <router-outlet></router-outlet>
    </div>
  </div>
</div>
/* You can add global styles to this file, and also import other style files */
.con{
  display:flex;
}
.con .left{
  width: 200px;
  background:#fffeee;
  height: 300px;
}
.con .left a{
  display: block;
  height: 44px;
  text-align: center;
}
.con .right{
  flex: 1;
}