Routing and Navigation in Angular | Mosh

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] in this section we're going to look at implementing routing and navigation so by the end of this section you will have an in-depth understanding of how routing works in angular and you'll be able to add navigation to your angular apps where specifically you're going to learn about configuring routes implementing single page applications working with route and query parameters and programmatic navigation now let's guess Darla so far you have seen a feel of the built-in modules in angular we abused the forms module the reactive forms module the HTTP module and now it's time to explore another module that is the router module so in this module we have a bunch of directives and services that we use for implementing navigation in our applications you're going to learn about this module throughout this section now there are three steps to implement navigation first we need to configure the route in our application each route determines what component should be visible when the user navigates to a certain URL so a route is the mapping of a path to a component second we need to add a router an outlet and that is where we display the corresponding component when a given route becomes active and finally we need to add links so over the next few lectures we're going to explore each of these steps in detail so here's a simple application we're going to work on throughout this section on the top we have a navigation bar with two links followers and posts the followers page is what we had as an exercise and a section about consuming HTTP services so note the URL in the browser's address bar that is slash followers when we click on a follower we go to a different URL that is profile slash and here we have two parameters the first one is the username and the second one is the user ID and after that we have a query string so we have a question mark with one query string parameter which is foo so you're gonna learn how to implement routes with multiple parameters and query strings in this section now we also have another link on our navigation bar that is posts which takes us to our posts page and note that the URL is slash posts so the first step to implement this navigation is to configure our routes now back in the project I'm gonna go to app module and configure our routes now if you want to code along with me download the zip file I've attached to this lecture then run npm install to install all the node packages and then ng serve okay all right now let's go to app that module so the first thing I want you to note here is that in the declarations array you're going to see a few new components so we've got navbar component which is a very simple bootstrap navigation component let me show you so navbar dot HTML very simple markup that I copied from bootstrap website so in this navigation bar we have two links followers and posts now back in app module the other components here are home component github profile component and not found component these are really basic components there is no code there is no markup I simply generated these with angular CLI for the purpose of this section now one more thing I want you to pay attention to is that here we have an import statement to import the router module from angular slash router so we have imported our router module now we're ready to define our routes so let's go to the imports array right here we're gonna call router module dot for route for route is a static method defined in the router module class and we use this to define the route route for our application now as our application grows we may want to break that application into smaller more manageable modules then in each module we're going to have a set of routes for that particular area of the application then instead of using for route we're gonna use for child you're gonna see this later in the course so for now don't worry about it so back to full route here we pass an array of routes each route is an object with two properties one is path and the other is component with this you're tilling angular router that whenever the browser address changes to this path display this component so here I'm gonna add the first route for our home page so the component should be home component and note that here we don't have a leading slash so none of our routes started with a slash and an empty pass represents the home page or the default route now let's add a comma here and duplicate this the second route is for our followers page so followers and the component is followers github followers component let's duplicate this again now when we click on a follower we want to see their profile so here for the third route the path should be something like this profile now here we want to add a parameter so slash and to add a parameter we use : and then we add the name of the parameter so user name so in this path we have a parameter called user name that will be placed dynamically at runtime you're going to see this later in this section now the component should be github profile component okay now we can reformat this code it's cleaner easier to the eyes all right this is much better now two more routes so let me duplicate this last route I'm gonna change the path to post and the component to post component now if the user navigates to a different URL that is not a valid route we want to display a typical not found page so let's duplicate this one more time now for the past I'm gonna use two asterisks this represents a wild card and this basically catches any URLs in the browser address bar so here I'm gonna change the component to not found component now the order of this route is important so if I put this last route at the beginning of our routes array this pattern this wild card is going to catch any route and we're only gonna see that not found page as another example let's change the as for this route to followers slash username so now with this configuration when we navigate to followers slash anything the path in the first route here will match the URL and as a result get how followers component will be displayed in other words with this configuration we will not be able to look at the profile of a given follower so we need to put more specific routes on the top so I'm gonna move this on top of the followers route so cut from here and paste it here so now the first route is more specific and if you have a URL with this pattern this route will be active and github profile component will be displayed so this is how we define routes next we're going to look at router outlet so we have defined our routes here in app module now if we switch over to the browser we're going to see an error so our generic error handler just kicked in and displayed this alert now let's take a look at the console so we have this error cannot find primary outlet to load home component so as I told you before the second step to implement routing is to add a router outlet and that's where angular router is going to display the component that is associated with the current route so let's go to app dot HTML so currently we only have the navigation bar now below that I'm gonna add a router outlet element this is a directive that is defined in the router module when angular sees this it's going to render the component associated with the current route after this router outlet so it's not going to render it inside this element let me show you so back in the browser alright we don't currently have any errors let's inspect this page so body we have app fruit we have our navbar here's our router outlet and this is our home component so you can see that it's not rendered inside router outlet it's rendered after this element all right now back to the page let's test our routes so currently we are at localhost for 4200 and as you can see our home component is visible now if I change this view RL to slash followers we get the list of followers beautiful so this route is working properly if I change this to followers / 1 we get the profile page perfect so our more specific route is working now if I change this to posts we get our posts page beautiful and finally if I change this to an invalid URL we get the nut found page so all the routes are working properly next we need to add links so as we click on these links in the navigation bar we get the right page currently this is not working properly now we're ready to add links so let's go to navbar dot HTML so currently we have two links on the navigation bar followers and posts and each of these links as you can see has an href attribute in angular applications we don't use this attribute let me show you why so I'm gonna change the value of this href attribute to slash followers and similarly for the second link I'm gonna change this to slash posts let's see what happens when we use the href attribute so back in the browser so currently we're on the home page but you can see the followers link in the navigation bar is highlighted I know this is a little bit confusing don't worry about that as we're gonna fix this in the next lecture but note that when I click under links in the navigation bar the page is going to flicker so I click on followers did you see the page flickered it went blank for a split second you're gonna see this again so I'm gonna click on posts look now this was too fast you probably didn't see it let me click on followers one more time with this kind of navigation every time we click on a link the entire page is downloaded and the angular app is reinitialized that's why the page goes blank for just a split second now as your application grows as you have more code the cost of startup is going to be higher so that delay will be even more now if you look at the browser Network tab so every time we click on any of these links here all the resources in our application are re downloaded so as an example you can see all our Java Script bundles are redownload that every time we click on a link this is something we want to avoid at all costs otherwise there is no point using angular to build modern applications when we click on a link we want only the content for the new page to be downloaded not the inter application not all the resources so to fix this problem instead of the href attribute we're going to use a directive called router link so I'm gonna replace this with router link and similarly here router link this directive is also defined in the router module now let's go back to the browser here first I'm going to refresh the page now open up the network tab these are all the resources that are downloaded the first time you open the application now I'm gonna clear all the items in this list ok now let's see what happens when we click on any of the links in the navigation bar so I'm gonna click followers first of all we didn't have a flickering effect the navigation bar stayed there the page didn't go blank only the content area was reloaded now let's go back to the network tab one more time here you can only see the request for the content of the followers page so these are the images of my followers in this list you are not going to see any JavaScript bundles re download it and you can verify this by filtering for JavaScript files look there is no JavaScript files there is no CSS files all of these resources were downloaded only the first time so we refer to applications built this way as single page applications so essentially a single page is downloaded from the server and as the user navigates from one page to another only the content of the target page is downloaded so single page applications or spas now before we finish this lecture let's go to our followers page and add a link for each follower so followers dot HTML so here we have a link for each follower I'm gonna replace this href with router link however this time we're dealing with a dynamic URL so we don't want to send the user to a page like followers slash 1 this parameter should be rendered dynamically when you're dealing with route parameters instead of using the router link as an attribute should use the property binding syntax so property binding and here instead of binding this to a string we should bind it to an expression in this expression we have an array the first element in this array is the path so that is slash followers after this first element we add all the route parameters so currently we have only one ralph's parameter so we can add that here follower that login if you want to render the username or follow our done ID it doesn't make a difference here so same back in the browser now here if I click the first follower we get to the profile page and note the URL in the browser's location bar so to recap for simple route you can use the router link directive as an attribute and set it to a string value if you're dealing with route parameters you should use the property binding syntax and set the value of this property to an array the first element in this array is the path and the subsequent elements are route arguments so currently we have a problem in this application the followers link and the navigation bar is always highlighted so if you go somewhere else the followers links still active let's see how we can fix this problem in navbar that component that HTML here we have this class active this is part of bootstrap so if you apply the active class on an Li in a navigation bar the corresponding link will be highlighted now we want to apply this dynamically so we have another directive called router linked active so just like we have router linked we also have router linked active and as the value here we set a string that includes a list of CSS classes that should be applied when this link is active so here we have only one CSS class that is active we can add more space current so all these classes should be separated by a space now similarly I'm gonna apply the same directive to the second li like this now let's test the application back in the browser so currently we are on the posts page and you can see the posts link and the nav bar is selected if i click on followers now the followers link is active and if we inspect this element so here's the Li for this link look at the class attribute here we have two classes active and current so we use the router link active to set the CSS class for the selected links in a navigation bar so in app module we have to find this round that takes a parameter username let me show you how we can extract this parameter in our github profile component because in a real world application most likely we want to get this parameter and use a service to get the profile of the given user so let's go to github profile the TS so here in github profile component in order to get access to route parameters we need to inject the activated route class in our constructor so here I add a parameter called route of type activated route this is a service that is defined in angular slash router library and is part of the router module that we imported earlier in this section now here in ng on in it we can get the route parameters from this object so this the route dot pram map that's the property that gives us all the parameters in this route now look at the type of this property it's an observable of pram map you have seen observables in the section about consuming HTTP services so you know that these observables have a method called subscribe we can subscribe to them and get values emitted in these observables so here I'm gonna call the SUBSCRIBE method you can see that here we need to pass a function that takes a parameter of type pram map and returns void so let's add an arrow function here for a map or we can call it params is shorter goes to a code block now let's log this on the console and see what is inside this object so console dot log perhaps save back in the browser so here in the list of followers I'm gonna click the first follower now let's take a look at the console so this is the object we get it has two properties keys and perhaps let's look at the keys so here we have only one key and that is username because in app module we set the name of our parameter to username okay now this object also has another property that is params and here we have key value pairs for route parameters and their values so this is the structure of a pram map object now back here in ng on in it let's look at the members defining this class so params dot we have get get all has and keys you saw the keys field this field returns all the keys or all the route parameters we use the get method to get the value of a given route parameter we use get all to get the value of all route parameters and has to see if we have a parameter by the given name in this object so here to get the value of the user name parameter we call the get method like this get user name and by the way what we have here is actually not user name it's user ID so always pay great attention to naming your route parameters because otherwise you can create confusion for other developers and this will also increase the cost of maintenance of your applications so let's go back to after module and change the name of this parameter to ID now back in github profile component here we need to get the value of the ID parameter now this method as you can see here in the intellisense returns a string if you need to work with a number a technique that we use in Java Script is to put a plus before this this will convert this string to a number now we can store it in a variable like ID and in a real world application we most likely send this to a service to get the profile of this user something like this service that get profile and we give it this ID now we don't need this for now so let's simply lock this on the console let's test the application one more time so here we have the user ID displayed in the console now if I go back to the followers list and click on a different user now in console we have two entries so this is how we get the route parameters but you might be wondering why this pram map is defined as an observable this makes it a little bit hard to access these parameters how come we don't have an API like this so this the route of ID this would be much easier right or potentially we could have listed route the pram map of I T this is easier to work with than an observable so in the next lecture I'm going to answer this question hi thank you for watching my angular tutorial if you enjoyed this video please like it and share it with others also you can subscribe to my channel for free new videos every week this video is part of my complete angular course with almost 30 hours of high quality content where you learn everything about angular from the basic to the advanced topics all in one course so you don't have to jump from one tutorial to another in case you're interested you can get this course with a big discount using the link in the video description and if not that's perfectly fine continue watching as the next section is coming up
Info
Channel: Programming with Mosh
Views: 228,837
Rating: 4.9173603 out of 5
Keywords: angular, angular.js, angularjs, angular 2, angular2, angular 4, angular4, mosh hamedani, javascript, jquery, routing, spa, code with mosh, programming with mosh, angular 4 router, angular 4 routing tutorial, angular routing, angular routing example, angular routermodule, angular routerlink, angular 4 routes, angular 4 routermodule, angular 4 routing
Id: tUCa3JcFILI
Channel Id: undefined
Length: 24min 32sec (1472 seconds)
Published: Wed Sep 06 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.