1. 程式人生 > >angular中路由的使用

angular中路由的使用

  1. 下載專案
    ng new angular-route --routing
    

     下載元件

    ng g component home
    ng g component news
    ng g component newscontent

      

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

    /**在路由當中引入各個元件 */
    import { HomeComponent } from './components/home/home.component';
    import { NewsComponent } from './components/news/news.component';
    import { NewscontentComponent } from './components/newscontent/newscontent.component';

      配置路由資訊

    const routes: Routes = [
      { 
        path: 'home',
         component: HomeComponent
      },
      { 
        path: 'news',
        component: NewsComponent
      },
      { 
        path: 'newscontent/:aid',
        component:NewscontentComponent
      },
      /**配置預設路由 */
      {
        path:"",
        redirectTo:"/home",
        pathMatch:"full"
      }
    ];

     

  3. 找到 app.component.html 根元件模板,配置 router-outlet 顯示動態載入的路由

  4. <h1>
      <a routerLink="/home" routerLinkActive="active">首頁</a>
      <br>
      <a routerLink="/news" routerLinkActive="active">新聞</a>
    </h1>
    <router-outlet></router-outlet>