angular中路由的使用
阿新 • • 發佈:2018-11-10
- 下載專案
ng new angular-route --routing
下載元件
ng g component home ng g component news ng g component newscontent
-
找到 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" } ];
-
找到 app.component.html 根元件模板,配置 router-outlet 顯示動態載入的路由
-
<h1> <a routerLink="/home" routerLinkActive="active">首頁</a> <br> <a routerLink="/news" routerLinkActive="active">新聞</a> </h1> <router-outlet></router-outlet>