
Posted on • Originally published atdanywalls.com
Learn Route Parameters in Angular with Example
When we build applications in Angular keep the communication of data between components or routes is important, sometimes we use a state manager, services or but take advantage of the url to provide information is a nice alternative. The url with combination of the router to send parameters to routes make very easy solve common communication challenges in our apps.
The Angular router enables us to add parameters to the URL by using therouterLink directive or theRouter service
, making it easy to provide information to routes and components. There are three types of parameters:required
,query
, andoptional
, each with its own role and advantages. In the following sections, we'll explain each type with examples using both therouterLink
andRouter service
.
Route Parameters
Required Route parameters are part of the URL path itself. They are used to specify a dynamic or static part of the URL, and we define the parameter in the route definition using a colon. For example:
{path:'user/:id',component:UserComponent}
UsingRouterLink
<a[routerLink]="['/user',userId]">View User</a>
UsingRouter
Service
this.router.navigate(['/user',this.userId]);
The final result is a url that expect the parameter 123
http://example.com/user/123
In this URL,123
serves as the route parameter forid
, representing the ID of the user you wish to display or manipulate within theUserComponent
.
Now, let's move on to query parameters.
Query Parameters
Query parameters appear after the question mark (?
) in the URL and are used for optional data that does not fit into the URL path structure and is not required to be registered in the routes. Similar to required parameters, we can use therouterLink
directive orRouter Service
.
UsingRouterLink
<a[routerLink]="['/search']"[queryParams]="{term:'angular',page:2}">Search</a>
UsingRouter
Service
this.router.navigate(['/search'],{queryParams:{term:'angular',page:2}});
Example URL:
http://example.com/search?term=angular&page=2
In this URL, there are two query parameters:term
, with a value ofangular
, andpage
, with a value of2
. These could be used for search functionality, indicating that the user is searching for "angular" and is currently on page 2 of the search results.
Matrix Parameters
Matrix parameters are a method to include optional parameters in the same part of a URL in Angular routing. This is helpful when you want to keep the state while navigating or use multiple parameters without changing the route structure.
For example the urlhttp://example.com/products;color=red;size=large
with matrix parameters in Angular, you can useRouterLink
in the template and theRouter
service in your code. Here's how to use matrix parameters in both situations:
UsingRouterLink
To use matrix parameters withRouterLink
, include them right in the link's path:
<a[routerLink]="['/products',{color:'red',size:'large'}]">Filtered Products</a>
This template example makes a link that, when clicked, goes to the/products
route with matrix parameterscolor=red
andsize=large
for that part of the route.
UsingRouter
Service
To use matrix parameters when navigating with theRouter
service, you need thenavigate
method. But unlike query parameters, matrix parameters are included in the route's path. Here's how to do it:
import{Component,Inject}from'@angular/core';import{Router}from'@angular/router';@Component({selector:'app-product-viewer',template:`<button (click)="navigate()">View Filtered Products</button>`})exportclassProductViewerComponent{route=inject(Router)navigate(){this.router.navigate(['/products',{color:'red',size:'large'}]);}}
In this example, calling thenavigate()
method (e.g., by clicking a button) directs the app to the/products
route withcolor
andsize
matrix parameters.
Now, let's apply these skills to solve a real-world problem.
Scenario
One friend contact us continue withhis project, he want show a list a products fromhttps://fakestoreapi.com/docs, when the user click on the product see details in a new page for likehttp://localhost:4200/products/1.
One more thing, if we can add show a discount link for users with the parameter "discount", looks complex ? nah! combining the required router parameters and query parameters to make it!
Let's do it!
The source code is part of my previous article aboutRouter Navigation
Setup Project
First, clone the repo and install all dependencies by runningnpm i
to have our project ready
git clone https://github.com/danywalls/play-with-angular-router.gitcdplay-with-angular-routernpm i
Run the project withnpm run start
, open the browserhttp://localhost:4200
Before start with need must to update ourapp.config.ts
to include essential services for routing and HTTP client functionalities and binding components.
provideHttpClient(
)
enable to use HttpClient with Injection.withComponentInputBinding():
help to bind information from theRouter
state directly to the inputs of the component inRoute
configurations.
exportconstappConfig:ApplicationConfig={providers:[provideRouter(routes,withComponentInputBinding()),provideHttpClient(),],};
Get The Products From API
We need to get the productos fromhttps://fakestoreapi.com/products, to do it, we a service using the CLIProductsService
$ng g s services/productsCREATE src/app/services/products.service.spec.ts(383 bytes)CREATE src/app/services/products.service.ts(146 bytes)
Next we going to define few steps to enable the service provide the information.
Declare a type to match with the products API response
Inject the
httpClient
to make the request to API.Declare
API
url variable.Define a property
$products
to bind the http response and transform to signals usingtoSignals
.
The final code looks like this:
import{inject,Injectable}from'@angular/core';import{HttpClient}from'@angular/common/http';import{toSignal}from'@angular/core/rxjs-interop';exporttypeProduct={id:string;title:string;description:string;image:string;price:string;};@Injectable({providedIn:'root',})exportclassProductsService{readonlyhttp=inject(HttpClient);readonlyAPI='https://fakestoreapi.com';$products=toSignal(this.http.get<Array<Product>>(`${this.API}/products`));}
We have theProductService
ready to provide the data, let's implement into thehome.component.ts
😊
Using Router Link and Show Products
Openhome.component.ts
and inject theProductService
and create a$products
property to get the list the products.
readonlyproductService=inject(ProductsService);$products=this.productService.$products;
Next, openhome.component.html
and use@for
to iterate over$products
. Render the image with therouterLink
directive, which takes two parameters: the route and the product id.
The final code looks like:
<divclass="products">@for(productof$products();trackproduct){<img[routerLink]="['../'+ ROUTE_TOKENS.HOME,product.id]"[src]="product.image"[alt]="product.description"/>}</div>
Save the changes, and we'll see the products.
However, there's one issue: the route`products/id`
doesn't exist yet. We need to declare it, so let's do that!
The Details Products
Our first step is generate theProductDetail
component and introduce a new route that allows navigating to a product's details:
$ng g c pages/product-detailsCREATE src/app/pages/product-details/product-details.component.html(31 bytes)CREATE src/app/pages/product-details/product-details.component.spec.ts(676 bytes)CREATE src/app/pages/product-details/product-details.component.ts(282 bytes)CREATE src/app/pages/product-details/product-details.component.scss(0 bytes)
next, open the app.routes.ts and add a new${ROUTE_TOKENS.HOME}/:id
pointing theProductDetailComponent
.
{path:ROUTE_TOKENS.HOME,component:HomeComponent,},{path:`${ROUTE_TOKENS.HOME}/:id`,component:ProductDetailsComponent,},
Perfect we have the product detail, but how get the id from the url parameter? did you rememberwithComponentInputBinding()
it allow us bind input properties from the router, sound interesting let's do it!
Binding Route Parameters
Open theproduct-detail.component.ts
and injectProductsService
, then we declare two new properties,id
typeinput
andproductSelected
.
$productSelected
: using computed function get the product selected when the id input signals changes.id
: it's the input bind by the match with the router.
exportclassProductDetailComponent{privatereadonlyproductService=inject(ProductsService);readonly$productSelected=computed(()=>{returnthis.productService.$products()?.find(({id})=>id==this.id());});id=input<string>('');}
Update theproduct-detail.component.html
markup to use the$productSelect
value.
<divclass="product-detail"><h3>{{$productSelected()?.title}}</h3><p>{{$productSelected()?.description}}</p><img[src]="$productSelected()?.image"/><span>{{$productSelected()?.price}}</span></div>
Save the changes. Now, when you click on a product, it navigates to the new route and displays all of the product details.
Excellent, we now have the product details with the necessary ID parameters, but we're missing the discount query parameters. Let's complete the final part.
The Discount Query Parameter
We want when the user click in a discount link send the query parameter and show some information about the discount in the product.
First, we use therouterLink
with thequeryParams
binding the queryParams and send on it the object{ discount: true }
, also we use thequeryParamsHandling
to merge.
Open theabout.component.html
, and add the following code snippet:
<a[routerLink]="['../'+ROUTE_TOKENS.PRODUCTS,1]"[queryParams]="{discount:true}"queryParamsHandling="merge"> Get something with discount</a>
Save the changes, and when you click the "Get something with discount" link, it sends the query parameter "discount."
Our final step is to read the query parameters. We make a small change in theProductsService
by adding a new property$discount
. It takes thequeryParamMap
fromActivatedRouter
and retrieves the discount parameter. We transform thequeryParamMap
observable into signals using thetoSignal
method.
The final code looks like:
readonly$discount=toSignal(inject(ActivatedRoute).queryParamMap.pipe(map((params)=>params.get('discount')),),);
Open theproduct-details.component.ts
file and add a new property$discount
, then bind it with theProductService.$discount
.
readonly$discount=this.productService.$discount;
Finally, edit theproduct-details.component.html
to read the$discount
property and display the message only when the discount is true.
@if ($discount()) {<span>Congrats you got 5% discount!</span> }
Save the changes and experiment with the discount feature in our app.
Conclusion
Yes, we've learned how to work with parameters in Angular, introducing a detailed view of our product offerings and the ability to feature special promotions via query parameters and how easy is to send parameters using therouterLink
and read them using theRouterService
. By combining this withActivatedRoute
, we can read values and provide data for our application routes.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse