Route Parameters - Pass Dynamic Data, Optional Route Params
Route params are very similar to query parameters, which we discussed in the previous part.
However, route params are cleaner, more readable, and more SEO-friendly.
What are Route Parameters?
Route parameters allow you to pass dynamic data through the URL path from one page to another.
You might say:
“We already did this using query params.”
Yes, that’s correct — query params and route params serve the same purpose, but the way data appears in the URL is different.
Query Params vs Route Params
Query Params Example:
Problems:
- Not very readable
- Not SEO-friendly
Route Params Example:
Benefits:
- Clean URL
- Better readability
- SEO-friendly
Drawback of Route Params
One small issue with route params is that you cannot easily identify what a value represents just by looking at it.
For example:
- Is
29an age, ID, or house number? - This clarity exists in query params but not in route params
Even then, route params are preferred due to cleaner URLs.
Step 1: Define Route Params in Routes File
Go to app.routes.ts and define route params using :.
Now your app supports:
/about/about/Anil/about/Anil/29
Step 2: Pass Route Params using RouterLink (Static)
home.html
Without route params, the page will not open because Angular expects required params.
Step 3: Pass Route Params using RouterLink (Dynamic)
home.ts
home.html
Now route params are passed dynamically.
Step 4: Read Route Params using ActivatedRoute
Go to about.ts.
Step 5: Display Route Params in HTML
about.html
Step 6: Pass Route Params on Button Click
home.ts
home.html
Making Route Params Optional (Important)
Route params cannot be optional by default.
To make them optional, we define multiple routes:
This allows:
- No params
- One param
- Multiple params
Do not add empty slashes (/) — it will break routing.