Lekhnath
Lekhnath

Reputation: 4625

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/[email protected]'

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/[email protected]

Upvotes: 2

Views: 450

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657446

'' 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

Upvotes: 3

Related Questions