URL Parameters
Route parameters are useful when the same Web Component should be rendered for a number of paths, where a part of the path is static, and another part contains a parameter value.
For example, both /user/1
and /user/42
paths can have the same route to render the content. The /user/
part is static, and 1
and 42
are the parameter values.
Route parameters are defined using an express.js-like syntax. The implementation is based on the path-to-regexp library that is commonly used in modern front-end libraries and frameworks.
The following features are supported:
Named parameters:
/profile/:user
Optional parameters:
/:size/:color?
Zero-or-more segments:
/kb/:path*
One-or-more segments:
/kb/:path+
Custom parameter patterns:
/image-:size(\d+)px
Unnamed parameters:
/(user[s]?)/:id
Routes for the above features can be defined as follows:
const router = new Router(document.getElementById('outlet'));
router.setRoutes([
{path: '/', component: 'x-home-view'},
{path: '/profile/:user', component: 'x-user-profile'},
{path: '/image/:size/:color?', component: 'x-image-view'},
{path: '/kb/:path*', component: 'x-knowledge-base'},
{path: '/image-:size(\\d+)px', component: 'x-image-view'},
{path: '/(user[s]?)/:id', component: 'x-profile-view'},
]);
Accessing Route Parameters
Route parameters can be accessed in the location.params
property of the route component.
The location
property is defined by the router.
Named parameters are accessible by a string key, such as
location.params.id
orlocation.params['id']
.Unnamed parameters are accessible by a numeric index, such as
location.params[0]
.