Angular Common Routing TasksThe command uses the Angular CLI to generate the basic Angular application with an application routing module called AppRoutingModule. NgModule is used to configure your router. In the below example, the application name is routing-app. The CLI prompts to select the CSS or a CSS pre-processor when generating a new application. Adding Components for RoutingAn application needs two components to navigate one to another to use the Angular router. To create a component by using the CLI, enter the command line where the first is the name of your Component: If you write First-Component, your Component would be FirstComponent. The guide works with CLI-generated Angular applications. If you are working manually, make sure your index.html file has a <base href="/"> in the <head>. Importing new componentsTo use new components, import into the AppRoutingModule at the top of the file as given below: There are three basic building blocks to building a route:Import AppRoutingModule in AppModule and add it to the imports array. If you create an application manually or work with an existing, non-CLI application, verify the configuration is correct or not. The following is the default AppModule that uses the CLI with the --routing flag. 1: Default CLI AppModule by the routingImport the router module to your routing module. Angular CLI does the step automatically. The CLI also sets up a routing array for your routes and configures the import and export arrays for @NgModule (). 2: CLI application routing module3: Define routes in your routes array.Each route in the array is a JavaScript object with two properties. The first path defines the URL path. The second property, Component, defines the Component that Angular uses for relative paths. Add routes to your application.Assign the anchor tag you want to add in the route to the RouterLink attribute. When the user clicks on each link, set the attribute's value on the Component to show. Update your component template to include <router-outlet>. The element informs Angular to update the application view with the Component for the selected route. Template with RouterLink and router-outletRoute orderThe router is important because the router uses the first match-winning strategy when matching routes, so more-specific routes are placed above less-specific routes. You can use a route to pass the type of information to your application components. Import ActivatedRoute and ParamMap to your Component. The import statements add several important elements that the Component requires. RouterActivatedRoute Inject an instance of ActivatedRoute by adding it to the application's constructor: ngOnInit() method is used to access the ActivatedRoute and track the id parameter: Note: The example uses a variable name and assigns it a value based on the name parameter.Set Wildcard RouteA well-functioning application should handle when a user tries to navigate a part of your application that doesn't exist. To add the functionality to the application, you set up a wildcard route. The angular router selects the route when the requested URL does not match the router path. Two asterisks, **, indicate that the definition of this route is a wildcard route. Common options include an application-specific PageNotFoundComponent, which you can define to display a 404 page to your users or redirect them to the main Component of your application. Display 404 pageTo display the 404 page, set up a wildcard route with Component property set to the component you want to use for 404 page: The last route with a path of ** is a wildcard route. The router selects the route if the requested URL does not match any earlier paths in the list and sends the user to PageNotFound Component. Set up redirectsIt configures a route with the path you want to redirect. In the example, the third route is a redirect where the router defaults to the first-component route. Nesting routeYou may route relative to a component other than your parent component as your application becomes more complex. \Here, AppComponent has its own <nav> and another <router-outlet> in addition to First Component. A child route is another route in that it requires both a path and a component. One difference is that you keep the child routes in the children array within the parent route. Using Relative PathsThe wildcard route comes last because it matches each URL, and the router picks it up only if no route matches first. Get Route InformationYou want the Component to retrieve the ID for the grocery item to display the correct information to the user. You can use a route to get the type of information to the application components. You can use ./ to specify the current level. Specifying a relative routeUse the Navigation Additional relative property in the component class to specify a relative route, import the navigation extras from @angular/router. The link parameter array containing the items set an object with the corresponding property to the active root. RelativeTo The goToItems() method interprets that the destination URL is relative to the active route and navigates to the item route. Accessing Query ParametersThe feature of your application requires access to the part of the root, such as a query parameter or a fragment. The Tour of Heroes application uses a list view. Component import statementsNext, inject the activated route service: Configure the class to have an observable, hero$, selected to hold the hero's id number and heroes. In ngOnInit(), add the following code to get the selected hero's id. The code snippet assumes that you have a list of heroes, a hero service, a function to get your heroes, and HTML to render your list and description, as in the Tour of Heroes example. Component 1 Import the following members in the component that you want to navigate. Component 2Inject ActivatedRoute in the constructor of the component class. Lazy loadingInstead of loading all modules as required, you can configure your router to lazy load modules that Angular loads modules only when the application is launched. Prevent unauthorized accessUse Root Guard to prevent users from navigating to certain parts of an application without authorization. The following root guards are available in Angular:
Create a service for your guard:The below example uses enabled to protect the route. In your routing module, use the below property in the routes configuration. Link parameters arrayA link parameter array contains the following content for router navigation:
You can bind the RouterLink directive to an array: The below is a two-element array which specifying route parameters: You can provide an optional route parameter to an object, such as {foo: 'foo' }: The examples cover the needs of an application with one level of routing. However, with a child router, you create new link array possibilities. The below minimal RouterLink example creates a specified default child route for the crisis center. The first item in the array identifies the original route (/crisis-center).
The first item in the array identifies original route (/crisis-center).
You can redefine the AppComponent template with crisis center routes: The link parameter array provides the flexibility to represent any routing depth to any legal sequence of route paths, router parameters, and route parameter objects. Location Strategy and Browser URL StylesThe router can create a "natural" URL indistinguishable from one that would require a page load. Older browsers send page requests to the server when the URL changes unless followed by a "#" (known as a "hash"). Routers take advantage of this exception by creating an in-application route URL with a hash. Here is a "hash URL" that leads to the crisis center. The router supports both styles with two location strategy providers:
You have the option to switch to HashLocationStrategy with an override during the bootstrapping process. Choosing a Routing StrategyRendering critical pages on the server is a technique that significantly improves perceived responsiveness when the application first loads. An application that would otherwise take ten or more seconds to start up can be presented on a server and delivered to a user's device in less than a second. <base href>The router uses the browser's history. PushState allows you to customize in-application URL paths. For example, localhost: 4200/crisis-center. In-application URLs may be indistinguishable from server URLs. The developers use HTML5 URLs in two steps:
Path Location StrategyNext TopicAngular ng-module |