Lekhnath Lekhnath - 4 months ago 28
AngularJS Question

Angular router 3 wildcard matching

What is wrong with following route configuration? I am always navigated to

**
even if there is a route for
app/jungle
.

import {bootstrap} from '@angular/platform-browser-dynamic';


import { RouterConfig, provideRouter } from '@angular/router@3.0.0-beta.2'

import {App} from './app';
import { HomeComponent } from './home.component';
import { JungleComponent } from './jungle.component';
import { NotFoundComponent } from './not-found.component';



const APP_ROUTES: RouterConfig = [
{
path: '', pathMatch: '', redirectTo: 'app/home'
},
{
path: 'app/', pathMatch: '', redirectTo: 'app/home'
},
{
path: 'app/home', component: HomeComponent
},
{
path: 'app/jungle', component: JungleComponent
},
{
path: '**', component: NotFoundComponent
}
]

bootstrap(App, [provideRouter(APP_ROUTES)])
.catch(err => console.error(err));


Here is a plunker.
I am using @angular/router@3.0.0-beta.2

Answer

'' is an invalid value for pathMatch.

pathMatch supports full and prefix. prefix is the default.

Set it to 'full' for the first two routes:

{
  path: '', pathMatch: 'full', redirectTo: 'app/home'
},

{
  path: 'app/', pathMatch: 'full', redirectTo: 'app/home'
},

{
path: 'app/home', component: HomeComponent
},

{
  path: 'app/jungle', component: JungleComponent
},

{
  path: '**', component: NotFoundComponent}
]

Plunker example

Update (according to the comment below)

I don't know exactly why the trailing / makes it work but I would use componentless parent routes instead like

const APP_ROUTES: RouterConfig = [
{ path: '', pathMatch: 'full', redirectTo: 'app/home' },
{ path: 'app', children: [
  { path: '', pathMatch: 'full', redirectTo: 'home' },
  { path: 'home', component: HomeComponent },
  { path: 'jungle', component: JungleComponent },
]},
{ path: '**', component: NotFoundComponent }]

Plunker example