Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Activating Routes with RouterLink in Angular

May 15, 2020 • 6 Minute Read

Introduction

Routing in Angular helps navigate from one view to another as users perform tasks in web apps. In this guide you will learn about Angular router's primary feature RouterLink and how to use routerLink in your Angular apps.

Angular Routing

You can configure an app's routes as an array of objects and pass them to Angular's RouterModule.forRoot.

File name: app.routes.ts

      import { RouteModule, Routes } from '@angular/router';

const routes: Routes = [
    { path: 'component-one', cmponent: ComponentOne }, { path: 'component-two', cmponent: ComponentTwo }
];
export const routing = RouterModule.forRoot(routes);
    

Then, import your routing configuration in the root of your app.

      import { routing } from './app.routes';
@NgModule({
   imports: [ BrowserModule, routing],
   declarations: [
      AppComponent,
      ComponentOne,
      ComponentTwo
   ],
   bootstrap: [ AppComponent ]
})
export class AppModule {}
    

By default, the app navigates to the empty route. You can redirect it to one of the named routes.

File name: app.routes.ts

      {path: '', redirectTo: 'component-one', pathMatch: 'full'}
    

The pathMatch property, which is required for redirects, tells the route how it should match the URL provided in order to redirect to the specified route. Since pathMatch: full is provided, the route will redirect to component-one if the entire URL matches the empty path('').

Linking Routes in HTML

To add links to one of the routes, use the routerLink directive in HTML. This directive accepts an array. The first parameter is the name of the route, and the second parameter is the parameters that you want to pass with the route.

      <a [routerLink]="['component-one', routeParams]"></a>
    

If you use the routerLink directive without the brackets, you'll need to pass the route as a string.

      <a routerLink="/component-one"></a>
    

You can also change the route programmatically in Angular.

      this.router.naigate(['/component-one']);
    

The <router-outlet> </router-outlet> acts as a placeholder for components. Angular dynamically adds the component for the route to be activated into this.

Accessing Route Parameters in Angular

The router provides two different methods to grab the route parameters. They are:

Snapshot

The ActivatedRoute service provides a snapshot of the current route.

      import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/route';

@Component({
     ...
})
export class SampleComponent implements OnInit {
     constructor(private route : ActivatedRoute) {}

ngOnInit() {
    this.myParam = this.route.snapshot.params.myParam;
}
}
    

This is simple and enough. But since Angular reuses the components for performance, this method won't work for some cases, for example, if you navigating from /product/1 or /product/2. In that case you need to use the Observable/Stream method.

Observable/Stream

This method uses observables, and when you navigate from one route to another route the observable will pass along the new data. Angular v4+ routers provide ParamMap, which is an observable you can use.

      ngOnInit() {
  // subscribe to the parameters observable
  this.route.paramMap.subscribe(params => {
    console.log(param.get('myParam'));
    this.myParam = params.get('myParam');
  })
}
    

If you are working with Angular versions prior to v4, you can grab route parameters with params instead of paramMap.

      ngOnInit() {
  // subscribe to the parameters observable
  this.route.params.subscribe(params => {
    console.log(params.get('myParam'));
    this.myParam = params.get('myParam');
  });
}

## Using a Child Route in Angular

While some routes may only be accessible and viewed within other routes, it may be appropriate to create them as child routes, for example, if you have a product route with an individual ID and want to navigate to other routes to see its overview or specification.

The children property in the routes accepts an array of child routes. You can use the same <router-outlet> directive to hold the child component.

File name: `app.routes.ts`
```typescript
export const routes: Routes = [
{ path: 'product-details/:id', component: ProductDetails,
    children: [
       { path: '', redirectTo: 'overview', pathMatch: 'full',
       { path: 'overview', component: Overview },
       { path: 'specification', component: Specification }
     ]
  }
}
    

Query and Route Parameters

The key difference between query parameters and route parameters is that route parameters are essential to determining a route, whereas query parameters are optional. The optional parameters are equal to /product-list?page=2 where as route parameters are /product-list/2.

      // Pass query params in router link
<a [routerLink]="['product-list']" [queryParams]="{ page: 2 }"> Go to Page 2</a>

// query parameters programmatically
this.router.navigate(['/product-list'], {  queryParams: {  page: pageNum } });
    

To read the query parameters, subscribe to queryParams in the ActivatedRoute.

      ngOnInit() {
  this.sub = this.route.queryParams.subscribe(params => {
      this.page = +params['page'] || 0;
  });
}
    

Conclusion

In this guide, we have explored how to activate routes in Angular with routerLink. We have also seen how to link routes in HTML, access parameters using child parameters, and the difference between query parameters and route parameters.

You can learn more about Angular in my guide Understanding the Purpose of Routing in Angular.