Navigate Between Routes in Angular with routerLink

Sam Julien
InstructorSam Julien

Share this video with your friends

Send Tweet
Published 2 years ago
Updated a year ago

Once routing is set up, we can add a new route by adding a new component and adding a path to our routes array in app.module.ts. But how do we navigate between the two routes? In this lesson, I'll show you how to use routerLink to switch between the routes without causing the page to refresh.

Sam Julien: [0:00] With routing set up, we can go ahead and add a second component to create a second route. To do that, let's open up a terminal. We're going to run ng generate component. If you'd like, you could abbreviate this and just say ng g c. Let's call it account.

[0:17] We'll let that generate. I'll go ahead and hide the terminal. To add a new route, let's just duplicate this line here. Over in our path, we'll just say account. In our component, we'll just use that new AccountComponent that we created.

[0:33] Now if I go over to our URL bar here and type in /account, you can see that we see account works, which is it's coming from the template that was created. If I go back over to the code and open account.component.html, you can see that same account works.

[0:51] We don't really have any way of navigating between our home component and our account component here. Let's add a little navigation bar and we'll do that in our app-component.html because that's where our router-outlet is.

[1:06] I'm going to go above our router-outlet here and I'm going to take advantage of Emmet, which is built into Visual Studio Code. I can just type nav and I'm going to make an unordered list and then I'm going to need two list items. I want each of these to have an a tag with them and then I'll just hit tab.

[1:26] You can see that Emmet just generated all that HTML for us, which is really, really nice. The first link is going to be / and we're going to say Home. The second one is going to be /account and we'll say Account.

[1:41] Right now, these are just regular HREFs, hyper references. Watch what happens if I click on Account. It's hard to see, but you can see the entire page reloading when I do that. Instead, what we want to do is use something built into Angular called a routerLink.

[2:02] If I replaced the HREF with routerLink which comes from Angular and then click on Home and Account, notice that there's no more loading in the window there. routerLink does a lot of other things too. We'll see in future lesson using routerLink for things like route parameters, and variables, and things like that.

[2:25] For now, this is the most basic way that you can navigate between routes and components in Angular.