Learn Angular.JS from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

Angular Routing Overview

Ranjan P.
11/10/2017 0 0
a. Routes:
The browser is a familiar model of application navigation:
  • Enter a URL in the address bar and the browser navigates to a corresponding page.
  • Click links on the page and the browser navigates to a new page.
  • Click the browser's back and forward buttons and the browser navigates backward and forward through the history of pages you've seen.
The Angular Router ("the router") borrows from this model. It can interpret a browser URL as an instruction to navigate to a client-generated view. It can pass optional parameters along to the supporting view component that help it decide what specific content to present. You can bind the router to links on a page and it will navigate to the appropriate application view when the user clicks a link. You can navigate imperatively when the user clicks a button, selects from a drop box, or in response to some other stimulus from any source. And the router logs activity in the browser's history journal so the back and forward buttons work as well.
b. The Basics:
This guide proceeds in phases, marked by milestones, starting from a simple two-pager and building toward a modular, multi-view design with child routes.
An introduction to a few core router concepts will help orient you to the details that follow.
Most routing applications should add a  element to the index.html as the first child in the  tag to tell the router how to compose navigation URLs.
If the app folder is the application root, as it is for the sample application, set the href value exactly as shown here.
c. Router imports:
The Angular Router is an optional service that presents a particular component view for a given URL. It is not part of the Angular core. It is in its own library package, @angular/router. Import what you need from it as you would from any other Angular package.
Code - import {RouterModule, Routes} from '@angular/router';
d. Configuration:
A routed Angular application has one singleton instance of the Router service. When the browser's URL changes, that router looks for a corresponding Route from which it can determine the component to display.
A router has no routes until you configure it. The following example creates four route definitions, configures the router via the RouterModule.forRoot method, and adds the result to the AppModule's imports array.
const appRoutes: Routes = [{path: 'crisis-center', component: CrisisListComponent}, {path: 'hero/:id', component: HeroDetailComponent}, {path: 'heroes', component: HeroListComponent, data: {title: 'Heroes List'}}, {path: '', redirectTo: '/heroes', pathMatch: 'full'}, {path: '**', component: PageNotFoundComponent }]; @NgModule({imports: [RouterModule.forRoot( appRoutes, {enableTracing: true} //
The appRoutes array of routes describes how to navigate. Pass it to the RouterModule.forRoot method in the module imports to configure the router.
Each Route maps a URL path to a component. There are no leading slashes in the path. The router parses and builds the final URL for you, allowing you to use both relative and absolute paths when navigating between application views.
The :id in the second route is a token for a route parameter. In a URL such as /hero/42, "42" is the value of the idparameter. The corresponding HeroDetailComponent will use that value to find and present the hero whose id is 42. You'll learn more about route parameters later in this guide.
The data property in the third route is a place to store arbitrary data associated with this specific route. The data property is accessible within each activated route. Use it to store items such as page titles, breadcrumb text, and other read-only, staticdata. You'll use the resolve guard to retrieve dynamic data later in the guide.
The empty path in the fourth route represents the default path for the application, the place to go when the path in the URL is empty, as it typically is at the start. This default route redirects to the route for the /heroes URL and, therefore, will display the HeroesListComponent.
The ** path in the last route is a wildcard. The router will select this route if the requested URL doesn't match any paths for routes defined earlier in the configuration. This is useful for displaying a "404 - Not Found" page or redirecting to another route.
The order of the routes in the configuration matters and this is by design. The router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. In the configuration above, routes with a static path are listed first, followed by an empty path route, that matches the default route. The wildcard route comes last because it matches every URL and should be selected only if no other routes are matched first.
If you need to see what events are happening during the navigation lifecycle, there is the enableTracing option as part of the router's default configuration. This outputs each router event that took place during each navigation lifecycle to the browser console. This should only be used for debugging purposes. You set the enableTracing: true option in the object passed as the second argument to the RouterModule.forRoot() method.
e. Router outlet:
Given this configuration, when the browser URL for this application becomes /heroes, the router matches that URL to the route path /heroes and displays the HeroListComponent after a RouterOutlet that you've placed in the host view's HTML.
Now you have routes configured and a place to render them, but how do you navigate? The URL could arrive directly from the browser address bar. But most of the time you navigate as a result of some user action such as the click of an anchor tag.
The RouterLink directives on the anchor tags give the router control over those elements. The navigation paths are fixed, so you can assign a string to the routerLink (a "one-time" binding).
Had the navigation path been more dynamic, you could have bound to a template expression that returned an array of route link parameters (the link parameters array). The router resolves that array into a complete URL.
The RouterLinkActive directive on each anchor tag helps visually distinguish the anchor for the currently selected "active" route. The router adds the active CSS class to the element when the associated RouterLink becomes active. You can add this directive to the anchor or to its parent element.
g. Router state:
After the end of each successful navigation lifecycle, the router builds a tree of ActivatedRoute objects that make up the current state of the router. You can access the current RouterState from anywhere in the application using the Routerservice and the routerState property.
Each ActivatedRoute in the RouterState provides methods to traverse up and down the route tree to get information from parent, child and sibling routes.
0 Dislike
Follow 2

Please Enter a comment


Other Lessons for You

.NET With AngularJS Training Program Syllabus
What You will Learn in .NET with AngularJS Training Program? Introduction to .Net: Features of .Net, CTS, CLS, CLR and MSIL. C# & .Net Basics and Branching & Flow Control. OOPs Concepts,...

Angular 4 Forms: Template Driven Approach
Angular Forms: Forms in Angular 4 can be designed on two approaches. As you can see below , we have a Template based design and the other being a Reactive based design. Here we will try to understand...

Introduction to Angular JS
What is AngularJS? AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly...

Javascript function
Q1.function f() { ... } var f = function() { ... };Which will work?Both will work. The difference here is that one is a named function ( function f() ) while the other is a variable equal to...

Top 6 Technology Trends for 2020
Technology has been evolving at a pace that the annual predictions about trends may seem to be outdated before they go live as a published blog post or article. The technology when evolves...

Looking for Angular.JS Classes?

The best tutors for Angular.JS Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Learn Angular.JS with the Best Tutors

The best Tutors for Angular.JS Classes are on UrbanPro

Book a Free Demo

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more