欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

angular中路由的使用

程序员文章站 2024-02-14 16:06:10
...
  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>