I had a subscription for egghead.io back when I started learning AngularJs. It's a great site for bite-sized videos on specific issues and development things. This particular video is free, and it's a great little demo for getting the "new" Angular router up and running
Here's the video on egghead.io: https://egghead.io/lessons/angular-2-configure-your-first-angular-2-route#/tab-code
I had recently scaffolded out a basic Angular 2 project with the Angular CLI. However, the Angular CLI (in it's current form, at least) doesn't set you up at all with routing. It can be a little intimidating trying to figure out where to put these things when you haven't set up routing in Angular 2 before, but John Lindquist does a nice job of keeping it super-simple, making it work, and then breaking things out into a cleaner, more encapsulated architecture.
I initially thought I could just scaffold out an Angular 2 project that had routing already set up for me, but boy did that cause problems for me! :) I feel bad trash talking the Angular Class Angular 2 Webpack Starter project because it actually is a really nice Angular 2 yeoman generator, but when I scaffolded the project I realized that it was set up with the the old "RouteConfig" method. This was a thing at one point, but it is deprecated now and won't work if you actually try to use it. Instead, the new version uses just "routes".
A basic Angular CLI scaffold will generate an app.module.ts file for you. In it's updates form we've imported appRoutes from an app.routes.ts file and then added it into the imports array passed into the NgModule metadata object.
I had to create the app.routes.ts file, but it's relatively simple:
Here I'm importing any components that are used (here it's just HomeComponent) and also the RouterModule. The export default is a nifty little way of making the syntax nice back in the app.module.ts file.
Of course you'll need to have a file that defines HomeComponent, but in terms of routing you're good to go once you have these two files set up! Note that in the video John shows you that you can define everything right in your app.module file, and it might be a good exercise for you to do this just to see how it all fits together. However, it's definitely a good coding practice in Angular development to have a separate file that's dedicated to just declaring routes which is why John breaks things out into the app.routes.ts file about halfway through the video. Anyway, that's the simple low-down on Angular 2 routing! Thanks John and the whole egghead.io team for putting this one out there for free!
If you're interested in taking a look at a simple Angular 2 project that has this type of routing implemented you can check out some of my code here: https://github.com/ParkBoys/Park-Boys-Bootcamp/tree/master/3-No-Doubts-Just-Routes/project.
The posts on this site are written and maintained by Jim Lynch. About Jim...
Want FREE access to
my daily stock tips
"The Triple Gainers"?
Sign up here!