I successfully integrated ngx-translate into my Angular project. Now, I want to dynamically change the base href based on the language selected from the header menu.
Currently, the URL appears as: "localhost:4200". However, upon launching the project, it should display either as "localhost:4200/en" or "localhost:4200/es", depending on the chosen language.
In my index.html file, I have the following:
<base href="/"/>
The header component's TypeScript file contains a function that switches the language using ngx-translate. Although 'replaceState' was used to reflect the chosen language in the URL, it reverts back when navigating 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);
}
}