# Angular Router
## 建置一個路由
```console
ng new routing-app --routing
```
## 路由文件
```javascript
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router'; // CLI imports router
const routes: Routes = []; // sets up routes constant where you define your routes
// configures NgModule imports and exports
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
```
## 宣告路由位置 sets up routes constant where you define your routes
```javascript
const routes: Routes = [
// 預設值
{ path: '',redirectTo:'hp', pathMatch:'full'},
// 路徑位置
{ path: 'path name', component: Component名稱},
{ path: 'path name/:path id/:path id', component: Component名稱},
];
```
## 設定萬用字元路由
```javascript
{ path: '**', component: }
```
## 設定重新導向
```javascript
const routes: Routes = [
{ path: 'first-component', component: FirstComponent },
{ path: 'second-component', component: SecondComponent },
// redirect to `first-component`
{ path: '', redirectTo: '/first-component', pathMatch: 'full' },
// Wildcard route for a 404 page
{ path: '**', component: PageNotFoundComponent },
];
```
## 巢狀路由
```javascript
const routes: Routes = [
{
path: 'first-component',
component: FirstComponent,
// this is the component with the <router-outlet> in the template
children: [
{
path: 'child-a', // child route path
component: ChildAComponent,
// child route component that the router renders
},
{
path: 'child-b',
component: ChildBComponent,
// another child route component that the router renders
},
],
},
];
```
## 資料來源
### 官方
[Angular 路由官方文件](https://angular.tw/guide/router)
### 其他
[如何使用 Angular Routing](https://ithelp.ithome.com.tw/articles/10225060)
[Angular 導航](https://jonny-huang.github.io/angular/training/05_angular_navigation/)
### 範例
[angular-45-router-demo - CodeSandbox](https://codesandbox.io/s/8p3r7o1q2?from-embed=&file=/src/app/models/product.ts)
[Angular (forked) - StackBlitz(list)](https://stackblitz.com/edit/angular-hsezw8?embed=1&file=src/app/app.component.html)
[Angular (forked) - StackBlitz(img)](https://stackblitz.com/edit/angular-ugunva?file=src%2Fapp%2Fapp.component.html)
###### tags: `Angular` `Router`