In-depth Guides
Routing

Other common Routing Tasks

This guide covers some other common tasks associated with using Angular router in your application.

Getting route information

Often, as a user navigates your application, you want to pass information from one component to another. For example, consider an application that displays a shopping list of grocery items. Each item in the list has a unique id. To edit an item, users click an Edit button, which opens an EditGroceryItem component. You want that component to retrieve the id for the grocery item so it can display the right information to the user.

Use a route to pass this type of information to your application components. To do so, you use the withComponentInputBinding feature with provideRouter or the bindToComponentInputs option of RouterModule.forRoot.

To get information from a route:

  1. Add withComponentInputBinding

    Add the withComponentInputBinding feature to the provideRouter method.

          
    providers: [  provideRouter(appRoutes, withComponentInputBinding()),]
  2. Add an Input to the component

    Update the component to have an Input matching the name of the parameter.

          
    @Input()set id(heroId: string) {  this.hero$ = this.service.getHero(heroId);}

    NOTE: You can bind all route data with key, value pairs to component inputs: static or resolved route data, path parameters, matrix parameters, and query parameters. If you want to use the parent components route info you will need to set the router paramsInheritanceStrategy option: withRouterConfig({paramsInheritanceStrategy: 'always'})

Displaying a 404 page

To display a 404 page, set up a wildcard route with the component property set to the component you'd like to use for your 404 page as follows:

      
const routes: Routes = [  { path: 'first-component', component: FirstComponent },  { path: 'second-component', component: SecondComponent },  { path: '**', component: PageNotFoundComponent },  // Wildcard route for a 404 page];

The last route with the path of ** is a wildcard route. The router selects this route if the requested URL doesn't match any of the paths earlier in the list and sends the user to the PageNotFoundComponent.

Preventing unauthorized access

Use route guards to prevent users from navigating to parts of an application without authorization. The following route guards are available in Angular:

To use route guards, consider using component-less routes as this facilitates guarding child routes.

Create a file for your guard:

      
ng generate guard your-guard

In your guard file, add the guard functions you want to use. The following example uses canActivateFn to guard the route.

      
export const yourGuardFunction: CanActivateFn = (  next: ActivatedRouteSnapshot,  state: RouterStateSnapshot) => {  // your  logic goes here}

In your routing module, use the appropriate property in your routes configuration. Here, canActivate tells the router to mediate navigation to this particular route.

      
{  path: '/your-path',  component: YourComponent,  canActivate: [yourGuardFunction],}

A link parameters array holds the following ingredients for router navigation:

  • The path of the route to the destination component
  • Required and optional route parameters that go into the route URL

Bind the RouterLink directive to such an array like this:

      
<a [routerLink]="['/heroes']">Heroes</a>

The following is a two-element array when specifying a route parameter:

      
<a [routerLink]="['/hero', hero.id]">  <span class="badge">{{ hero.id }}</span>{{ hero.name }}</a>

Provide optional route parameters in an object, as in { foo: 'foo' }:

      
<a [routerLink]="['/crisis-center', { foo: 'foo' }]">Crisis Center</a>

These three examples cover the needs of an application with one level of routing. However, with a child router, such as in the crisis center, you create new link array possibilities.

The following minimal RouterLink example builds upon a specified default child route for the crisis center.

      
<a [routerLink]="['/crisis-center']">Crisis Center</a>

Review the following:

  • The first item in the array identifies the parent route (/crisis-center)
  • There are no parameters for this parent route
  • There is no default for the child route so you need to pick one
  • You're navigating to the CrisisListComponent, whose route path is /, but you don't need to explicitly add the slash

Consider the following router link that navigates from the root of the application down to the Dragon Crisis:

      
<a [routerLink]="['/crisis-center', 1]">Dragon Crisis</a>
  • The first item in the array identifies the parent route (/crisis-center)
  • There are no parameters for this parent route
  • The second item identifies the child route details about a particular crisis (/:id)
  • The details child route requires an id route parameter
  • You added the id of the Dragon Crisis as the second item in the array (1)
  • The resulting path is /crisis-center/1

You could also redefine the AppComponent template with Crisis Center routes exclusively:

      
@Component({  template: `    <h1 class="title">Angular Router</h1>    <nav>      <a [routerLink]="['/crisis-center']">Crisis Center</a>      <a [routerLink]="['/crisis-center/1', { foo: 'foo' }]">Dragon Crisis</a>      <a [routerLink]="['/crisis-center/2']">Shark Crisis</a>    </nav>    <router-outlet />  `})export class AppComponent {}

In summary, you can write applications with one, two or more levels of routing. The link parameters array affords the flexibility to represent any routing depth and any legal sequence of route paths, (required) router parameters, and (optional) route parameter objects.

LocationStrategy and browser URL styles

When the router navigates to a new component view, it updates the browser's location and history with a URL for that view.

Modern HTML5 browsers support history.pushState, a technique that changes a browser's location and history without triggering a server page request. The router can compose a "natural" URL that is indistinguishable from one that would otherwise require a page load.

Here's the Crisis Center URL in this "HTML5 pushState" style:

      
localhost:3002/crisis-center

Older browsers send page requests to the server when the location URL changes unless the change occurs after a "#" (called the "hash"). Routers can take advantage of this exception by composing in-application route URLs with hashes. Here's a "hash URL" that routes to the Crisis Center.

      
localhost:3002/src/#/crisis-center

The router supports both styles with two LocationStrategy providers:

Providers Details
PathLocationStrategy The default "HTML5 pushState" style.
HashLocationStrategy The "hash URL" style.

The RouterModule.forRoot() function sets the LocationStrategy to the PathLocationStrategy, which makes it the default strategy. You also have the option of switching to the HashLocationStrategy with an override during the bootstrapping process.

HELPFUL: For more information on providers and the bootstrap process, see Dependency Injection.