[Fixed] Angular 2 optional route parameter

Issue

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'
}])

Solution

You can define multiple routes with and without parameter:

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

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

Leave a Reply

(*) Required, Your email will not be published