Reputation: 1572
I can't believe I can't find this situation already covered here in SO: (I found examples with additional parameter with and without for each single route, but it's unacceptable)
So I have
RouterModule.forRoot([
{
path: 'home',
component: HomeComponent
},
{
path: 'news',
component: NewsComponent
},
{
path: 'newsDetail/:id',
component: NewsDetailComponent
},
...
})
So the example URLs would be
http://somewhere.com/home
http://somewhere.com/news
http://somewhere.com/newsDetail/10
What if I want to add optional parameter to each of those URLs, so I can explicitly call another localization directly in URL (for permalinks):
http://somewhere.com/home/en
http://somewhere.com/news/en
http://somewhere.com/newsDetail/10/en
So it should work with and without "/en" at the end - and of course adding to each and every route (same route with optional /:language) is not the answer (imagine dozens of pages involved, many of them already with their own parameters)
Upvotes: 0
Views: 436
Reputation: 71891
If you want the language parameter to be the first, you can do the following. You will first have to declare an empty app or whatever root component and use this in the bootstrap instead of the AppComponent
:
@Component({
selector: 'app-root',
template: `<router-outlet></router-outlet>`
})
export class RootComponent {}
Then create a module from your current routes, if you do not have that already. Call it AppRoutingModule
.
export const AppRoutes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'news', component: NewsComponent },
{ path: 'newsDetail/:id', component: NewsDetailComponent }
];
@NgModule({
imports: [RouterModule.forFeature(AppRoutes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
Then create a RootRoutingModule
, which will do the magic:
export const RootRoutes: Routes = [
{ path: '', loadChildren: () => import('./app.module').then((m) => m.AppModule) },
{ path: 'en', loadChildren: () => import('./app.module').then((m) => m.AppModule) }
];
@NgModule({
imports: [RouterModule.forRoot(AppRoutes)],
exports: [RouterModule],
})
export class RootRoutingModule {}
The issue with this, is that you'll have to hardcode all the languages you might support, as I don't think a :language
parameter will work
So basically, create a root module which will do the language routing and the bootstrapping
Upvotes: 1