My website supports multiple languages with a dropdown menu allowing users to switch between English and German.
This component in my application's footer triggers the changeLanguage() function when the language selection is changed:
constructor(
private pageService: PageService,
private router: Router,
private el: ElementRef,
private cd: ChangeDetectorRef,
private meta: Meta,
private route: ActivatedRoute
) { }
ngOnInit(): void {
var nativeElement: HTMLElement = this.el.nativeElement,
parentElement: HTMLElement = <HTMLElement>nativeElement.parentElement;
// move all children out of the element
while (nativeElement.firstChild) {
parentElement.insertBefore(nativeElement.firstChild, nativeElement);
}
// remove the empty element(the host)
parentElement.removeChild(nativeElement);
this.routerSub$ = this.router.events.subscribe(event => {
if (event != null) {
if (event instanceof NavigationEnd) {
this.languageCode = SiteContext.getLanguageCode(event.urlAfterRedirects);
if (this.languageCode == "en" && this.selectedLanguage.name == 'Deutsch') { this.selectedLanguage = this.languages[1]; }
}
}
});
}
ngAfterViewInit() {
}
ngOnDestroy() {
if (this.routerSub$ != null) this.routerSub$.unsubscribe();
this.subscriptions.forEach((subscription: Subscription) => { subscription.unsubscribe(); });
this.subscriptions = [];
}
changeLanguage(lang) {
let langCode: string = (lang.name == 'Deutsch' ? "de" : "en");
this.router.navigate([langCode, 'home']);
}
Upon changing the language selection, the app should redirect to either '/de/home' or '/en/home/' and display content accordingly.
The initial language change functions perfectly, updating the URL and loading new content. However, subsequent changes do not trigger any action after running the changeLanguage() function.
It appears to be related to reusing routes in an Angular v5 build, but solutions found on Stack Overflow have not resolved the issue.
I've focused on implementing RouteReuseStrategy shouldDetach for specific routes in Angular 2, as suggested by this question. Additionally, I am integrating the CustomReuseStrategy class from that answer.
For additional context:
app.routing.ts:
const appRoutes: Routes = [
//{ path: '', redirectTo: '/de/home', pathMatch: 'full' },
{ path: 'de/v2-home', component: HomeComponent, data: { animation: 'de/v2-home' } },
{ path: '', redirectTo: '/de/v2-home', pathMatch: 'full' },
{ path: ':lang/v2-home', component: HomeComponent, data: { animation: ':lang/v2-home' } },
];
app.module.ts:
import { RouteReuseStrategy } from "@angular/router";
@NgModule({
[...],
providers: [
{provide: RouteReuseStrategy, useClass: CustomReuseStrategy}
]
)}
export class AppModule {
}
If there are any errors in my navigation implementation, please point them out.
Thank you.