Jeroen Jeroen - 1 month ago 7
Javascript Question

Angular 2 optional route parameter

Is it possible to have an optional route parameter in the Angular 2 route? I tried the Angular 1.x syntax in RouteConfig but received below error:


"ORIGINAL EXCEPTION: Path "/user/:id?" contains "?" which is not allowed in a route config."


@RouteConfig([
{
path: '/user/:id?',
component: User,
as: 'User'
}])

Answer

You can define multiple routes with and without parameter:

@RouteConfig([{
  path: '/user',
  component: User,
  as: 'Usernew'},
{
  path: '/user/:id',
  component: User,
  as: 'User'
}])

and handle the optional parameter in your component:

constructor(params: RouteParams) {
    var paramId = params.get("id");

    if (paramId) {
        ...
    }
}

See also the related github issue: https://github.com/angular/angular/issues/3525

Comments