|
| 1 | +# 3. Add Angular Router With Config |
| 2 | + |
| 3 | +## Generate HelloNg Component |
| 4 | + |
| 5 | +```sh |
| 6 | +npx ng generate component HelloNg |
| 7 | +``` |
| 8 | + |
| 9 | +## Generate and update AppRoutingModule |
| 10 | + |
| 11 | +Note: If you initialise an Angular CLI project with the `--routing` flag this will automatically be created for you, so skip this step. |
| 12 | + |
| 13 | +```sh |
| 14 | +npx ng generate module routing/app-routing --module=app --flat |
| 15 | +``` |
| 16 | + |
| 17 | +Once generated, add routes and RouerModule imports and exports. |
| 18 | + |
| 19 | +[app.routing.module.ts](../src/app/routing/app.routing.module.ts) |
| 20 | + |
| 21 | +```ts |
| 22 | +const routes: Routes = []; |
| 23 | + |
| 24 | +@NgModule({ |
| 25 | + imports: [RouterModule.forRoot(routes)], |
| 26 | + exports: [RouterModule] |
| 27 | +}) |
| 28 | +export class AppRoutingModule { } |
| 29 | +``` |
| 30 | + |
| 31 | +## Configure Routes |
| 32 | + |
| 33 | +[app.routing.module.ts](../src/app/routing/app.routing.module.ts) |
| 34 | + |
| 35 | +```ts |
| 36 | +const routes: Routes = [ |
| 37 | + { |
| 38 | + path: 'hello-ng', |
| 39 | + component: HelloNgComponent |
| 40 | + } |
| 41 | +]; |
| 42 | +``` |
| 43 | + |
| 44 | +## Add RouterOutlet to AppComponent template |
| 45 | + |
| 46 | +[app.component.html](../src/app/app.component.html) |
| 47 | + |
| 48 | +```html |
| 49 | +<router-outlet></router-outlet> |
| 50 | +``` |
| 51 | + |
| 52 | +## Problem 1. Navigating to Angular Route Doesnt Work |
| 53 | + |
| 54 | +Navigate to [/hello-ng](http://localhost:4200/hello-ng). |
| 55 | + |
| 56 | +Now, the route doesn't load as you would expect. This is where we have to start hacking. |
| 57 | + |
| 58 | +## Debugging |
| 59 | + |
| 60 | +If you want to debug the routing you can update your `AppRoutingModule` as follows: |
| 61 | + |
| 62 | +[app-routing.module.ts](../src/app/routing/app-routing.module.ts) |
| 63 | + |
| 64 | +```ts |
| 65 | +imports: [RouterModule.forRoot(routes, |
| 66 | + { enableTracing: true } // <-- For debugging purposes only. Should be turned off in prod. |
| 67 | +)], |
| 68 | +``` |
| 69 | + |
| 70 | +We can force the Angular Router to kick in by adding a `routerLink` for our new Angular route. |
| 71 | + |
| 72 | +[app.component.html](../src/app/app.component.html) |
| 73 | + |
| 74 | +```html |
| 75 | +<nav> |
| 76 | + <a routerLink="/hello-ng">Hello Ng</a> |
| 77 | +</nav> |
| 78 | +``` |
| 79 | + |
| 80 | +If you click that link it should work and you should see some logging in the console. But if you refresh the page the route will not load. The presence of AngularJs UI router is causing Angular router not to work. To fix that, go to the next step. |
| 81 | + |
| 82 | +## Next step |
| 83 | + |
| 84 | +[Part 4: Hacks To Get Hybrid Routing Working](./part-4.md) |
0 commit comments