Angular routing生成路由和路由的跳轉
什么是路由
路由的目的是可以讓根組件按照不同的需求動態加載不同的組件。
根據不同地址,加載不同組件,實現單頁面應用。
Angular 命令創建一個配置好路由的項目
命令創建項目
ng new demo02 --routing
安裝依賴
npm install
啟動項目
ng serve --open
與沒有創建路由的項目比較
創建路由項目的文件比沒有創建路由項目的文件多了一個 app-routing.module.ts 文件。
然后在 app.module.ts 文件中引入了路由文件。
在 app.component.html 文件中加入了動態加載組件顯示的地方。
路由學習案例
創建組件
創建幾個組件,首先創建一個 components 文件夾存放將要創建的組件。
創建home組件
ng g component components/home
創建news組件
ng g component components/news
創建user組件
ng g component components/user
配置路由,點擊不同的導航顯示不同組件
在 app-routing.module.ts 中配置路由。
首先引入組件
// 引入組件 import {HomeComponent} from './components/home/home.component' import {NewsComponent} from './components/news/news.component' import {UserComponent} from './components/user/user.component'
配置路由
// 配置路由 const routes: Routes = [ { path:'home', component:HomeComponent, }, { path:'news', component:NewsComponent, }, { path:'user', component:UserComponent, } ];
添加導航按鈕
在根組件 app.component.html 文件中添加導航。
<header> <ul> <li><a routerLink="home" >首頁</a></li> <li><a routerLink="news" >新聞</a></li> <li><a routerLink="user" >用戶</a></li> </ul> </header>
我們最簡單的路由寫完了!!!
但是我們發現一個問題,當我們初始化整個項目的時候,默認是沒有組件的
我們如果想一進來就加載首頁組件,就涉及到默認的跳轉路由!
默認加載組件(空路由)
{ path:'', // 空路由 redirectTo:'home', // 重定向到 pathMatch:'full' }
如果路由輸入錯誤,還是跳回首頁(也可以匹配空路由)
// 匹配不到路由時候加載的組件 { path:'**', // 任意路由 component:HomeComponent }