'Change Angular base href with ngx-translate
I have already implemented ngx-translate succesfully. Now, I want to change the base href of my Angular project, depending on the language I choose from my header menu.
Currently, my URL looks like this: "localhost:4200". Then, when you launch the project, it must show something like this: "localhost:4200/en" or like this: "localhost:4200/es", depending on the choosen language.
My index html has this:
<base href="/"/>
And my header component ts file has a function that changes the language using ngx-translate. As you can see, I tried to use 'replaceState' to show the choosen language in the URL, and it worked, but it disappears once I navigate to another route.
import { Component, OnInit } from '@angular/core';
//For translate language
import { TranslateService } from '@ngx-translate/core';
import { Router, Event, NavigationStart, NavigationEnd } from '@angular/router';
import { Location } from '@angular/common';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss'],
})
export class HeaderComponent implements OnInit {
constructor(private translate: TranslateService,
private router: Router,
private location: Location,
)
{ translate.addLangs(['es','en']);
translate.setDefaultLang('es');
}
ngOnInit(): void {
}
useLanguage(language: string): void {
this.translate.use(language);
// alert(language);
// location.replace("https://www.google.com");
// return;
const modified_path = language;
this.location.replaceState(modified_path);
}
}
Solution 1:[1]
It looks like you are trying to achieve some kind of routing using base href. I would use base href only if I need multiple instances of my application. E.g. each of them in a subfolder.
Maybe you should give try on Angular Router (https://angular.io/guide/router-reference) if you want just one instance of the application handling different languages. The idea is to have a route on the root level that represents the language and a language guard that ensures only valid languages are called. This would look something like this:
const routes2: Routes = [
{
path: ':language',
canActivate: [LanguageGuard],
children: [
{
path: 'home',
component: HomeComponent,
},
{
path: 'some-page',
component: SomePageComponent,
},
]
},
{
path: '**',
redirectTo: '/en',
},
];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pateta |
