Reputation: 1555
I am struggling to get my route to work. I am using RouterLink which does not navigate to the route. My app.routing has
const routes: Routes = [
{
path: '',
redirectTo: '/',
pathMatch: 'full'
},
{
path: '',
component: LayoutComponent,
loadChildren: () => import('./views/main/main.module').then( m => m.MainModule )
}
];
The mainModule has the following
const routes: Routes = [
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
},
{
path: 'search',
component: SearchFormComponent,
loadChildren: () => import('../../views/search/search.module').then( m => m.SearchModule )
},
{
path: '**',
redirectTo: '/home',
pathMatch: 'full'
}
];
The mainModule declares and exports LayoutComponent
In LayoutComponent.html
<a class="nav-link" [routerLink]="'/search'">
Search
</a>
But when I click on the search in the UI, the route is not going to the search component. It stays on the Home component. Please help - where am I going wrong?
Upvotes: 0
Views: 3407
Reputation: 1555
Finally solved it by removing '' and ** and replacing them with
{
path: '',
component: HomeComponent,
},
Upvotes: 0
Reputation: 2721
Swap the order of your routes.
const routes: Routes = [
{
path: 'search',
component: SearchFormComponent,
loadChildren: () => import('../../views/search/search.module').then( m => m.SearchModule )
},
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
},
{
path: '**',
redirectTo: '/home',
pathMatch: 'full'
}
];
Angular router works with first come, first served.
The order of the routes in the configuration matters and this is by design. The router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. In the configuration above, routes with a static path are listed first, followed by an empty path route, that matches the default route. The wildcard route comes last because it matches every URL and should be selected only if no other routes are matched first.
From angular website here
As explained here
Update: Although it would still be an issue, so I'll leave the original answer here. Try setting your router link to
<a class="nav-link" [routerLink]="['search']">
Search
</a>
Upvotes: 1