I’m using the @jsverse/transloco
library in my Angular application to manage language translation. When I switch languages using a button, the translations are updated correctly in the template (for example, “en title” becomes “es title”). However, the link in my template doesn’t change accordingly.
The link is constructed using a custom lang
pipe that attaches the current language to the URL. Below is the code for my LangPipe
and the switchLang
method:
import { Component, inject, Injectable, isDevMode, Pipe } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import {
provideTransloco,
Translation,
TranslocoLoader,
TranslocoModule,
TranslocoService,
} from '@jsverse/transloco';
import { HttpClient, provideHttpClient } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { provideRouter, RouterModule } from '@angular/router';
console.clear();
@Injectable({ providedIn: 'root' })
export class TranslocoHttpLoader implements TranslocoLoader {
private http = inject(HttpClient);
getTranslation(lang: string) {
return this.http.get<Translation>(`/assets/i18n/${lang}.json`);
}
}
@Pipe({
name: 'lang',
})
export class LangPipe {
transloco = inject(TranslocoService);
transform(value: string) {
console.log({ value });
return `${this.transloco.getActiveLang()}/${value}`.replace(////g, '/');
}
}
@Component({
selector: 'app-root',
imports: [TranslocoModule, CommonModule, LangPipe],
template: `
in app!
<ng-container *transloco="let t">
<p>{{ t('title') }}</p>
<button (click)="switchLang()">switch lang</button>
<a [href]="'/products/1' | lang">goto to some link</a>
</ng-container>
`,
})
export class App {
name = 'Angular';
transloco = inject(TranslocoService);
switchLang() {
if (this.transloco.getActiveLang() === 'en') {
this.transloco.setActiveLang('es');
} else {
this.transloco.setActiveLang('en');
}
}
}
bootstrapApplication(App, {
providers: [
provideHttpClient(),
provideTransloco({
config: {
availableLangs: ['en', 'es'],
defaultLang: 'en',
reRenderOnLangChange: true,
prodMode: !isDevMode(),
},
loader: TranslocoHttpLoader,
}),
],
});
- The language is switching successfully in the template (
en
becomeses
), but the URL (generated by thelang
pipe) does not update with the new language. - The pipe transforms the URL as expected, but it doesn’t seem to react to the language change when it’s triggered by the
switchLang
method.
What I’ve tried:
- I’ve verified that the language changes correctly with the
transloco.getActiveLang()
method. - I’ve also checked the
lang
pipe, and it correctly transforms the link based on the active language, but it does not update dynamically when the language is switched.
If Transloco has a better built-in way to handle this scenario and update the URL correctly based on the active language, I would happily use that approach instead of the custom pipe.
How can I ensure that the URL updates correctly when the language is switched?