How to link an Angular component to a router.

There are plenty of tutorials about how to make angular apps. However, I struggle with remembering how this whole router thing works.
In a nutshell, components are like reusable bits of code, and you can ‘hotplug’ them into a router outlet.

To do that, first, you have to have a router-outlet component, usually in app.component.html

If it’s not already there, you might need to add this to app.module.ts

Now that you’ve got that, you can make a new component by using “ng generate component [name]”

If you did this, then ng would have already added several lines to your app.module.ts

Here are several of mine. It adds the word “Component” to the end of whatever name you put in there when you generated the part.

It should have also added them into the declarations array in @NgModule. If it didn’t, then you need to put them in here.

 

 

Now, you can add the routes. In @NgModule, there is an array called imports: []. Inside that array, there should be an element called RouterModule.forRoot([])

Inside that RouterModule.forRoot([]) array, you can add any routes you’d like. These end up being basically “links” back to your component that you generated earlier
This is what mine looks like:

You can pick any name you’d like for the “path”. And if you’d like, you can add multiple parts to the path – like you see here in my /Parts/:uidPart. This allows you to later pass things into your component through the routerlink.

 

Once you have those paths defined, you can bind them to the [routerLink] like this:

This particular link will end up displaying my /Parts router path – which will load the PartsComponent from above (because of the path that says Parts/:uidPart),¬† and pass it the uidPart that it took from the .ts file associated with this anchor’s HTML. Essentially, this ends up loading the url like this¬† /PartComponent/uidPart

If you don’t need to pass any data, then you can call your [routerLink], but leave off the second part of the array. In this example, it would be something like [routerLink] = “[‘/Parts’]”

That’s it!

 

Tom

Leave a comment

Your email address will not be published. Required fields are marked *