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.
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
1import { RouteModule, Routes } from '@angular/router';
2
3const routes: Routes = [
4 { path: 'component-one', cmponent: ComponentOne }, { path: 'component-two', cmponent: ComponentTwo }
5];
6export const routing = RouterModule.forRoot(routes);
Then, import your routing configuration in the root of your app.
1import { routing } from './app.routes';
2@NgModule({
3 imports: [ BrowserModule, routing],
4 declarations: [
5 AppComponent,
6 ComponentOne,
7 ComponentTwo
8 ],
9 bootstrap: [ AppComponent ]
10})
11export 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
1{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('')
.
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.
1<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.
1<a routerLink="/component-one"></a>
You can also change the route programmatically in Angular.
1this.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.
The router provides two different methods to grab the route parameters. They are:
The ActivatedRoute
service provides a snapshot of the current route.
1import { Component, OnInit } from '@angular/core';
2import { ActivatedRoute } from '@angular/route';
3
4@Component({
5 ...
6})
7export class SampleComponent implements OnInit {
8 constructor(private route : ActivatedRoute) {}
9
10ngOnInit() {
11 this.myParam = this.route.snapshot.params.myParam;
12}
13}
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.
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.
1ngOnInit() {
2 // subscribe to the parameters observable
3 this.route.paramMap.subscribe(params => {
4 console.log(param.get('myParam'));
5 this.myParam = params.get('myParam');
6 })
7}
If you are working with Angular versions prior to v4, you can grab route parameters with params
instead of paramMap
.
1ngOnInit() {
2 // subscribe to the parameters observable
3 this.route.params.subscribe(params => {
4 console.log(params.get('myParam'));
5 this.myParam = params.get('myParam');
6 });
7}
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
File name: app.routes.ts
1export const routes: Routes = [
2{ path: 'product-details/:id', component: ProductDetails,
3 children: [
4 { path: '', redirectTo: 'overview', pathMatch: 'full',
5 { path: 'overview', component: Overview },
6 { path: 'specification', component: Specification }
7 ]
8 }
9}
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
.
1// Pass query params in router link
2<a [routerLink]="['product-list']" [queryParams]="{ page: 2 }"> Go to Page 2</a>
3
4// query parameters programmatically
5this.router.navigate(['/product-list'], { queryParams: { page: pageNum } });
To read the query parameters, subscribe to queryParams
in the ActivatedRoute
.
1ngOnInit() {
2 this.sub = this.route.queryParams.subscribe(params => {
3 this.page = +params['page'] || 0;
4 });
5}
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.