How to Pass Query Parameters to Angular Routes Using routerLink Directive
Learn to pass optional query parameters using the routerLink directive and how to intercept and read those parameters in other Angular components.
Photo by Athena: https://www.pexels.com/photo/black-textile-910299/
Let’s assume you have the following routes defined:
const routes = [
{ path: '', component: AboutComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent },
];
Angular routing directives
In your markup file, if you want to navigate to the “ContactComponent”, you would use the routerLink directive, passing it the value “contact”.
<a class="nav-link" routerLink="contact">Contact</a>
This is pretty straightforward. But what if you want to pass some optional query parameters to the component? In that case, in addition to the routerLink directive, you must also add the queryParams directive. This directive can be bound to an object containing the parameters.
<a class="nav-link"
routerLink="contact"
[queryParams]="{ showEmail: true }">Contact & Email
</a>
In the example above, we pass the “showEmail” parameter with the value “true”.
Intercept optional query parameters in Angular components
Now that we have our markup, it’s time to modify the component and enable it to read the query parameter from the ActivatedRoute. We do that in the ngOnInit method, by subscribing to the queryParamMap observable.
@Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.css'],
})
export class ContactComponent implements OnInit {
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.queryParamMap.subscribe((paramMap) => {
// read param from paramMap
const paramValue = paramMap.get('showEmail');
// use parameter...
});
}
}